gpt4 book ai didi

javascript - JS : Get number of same values

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:13:06 26 4
gpt4 key购买 nike

假设我有这个数组:

[1, 2, 2, 3, 3, 3, 4]

我如何返回包含值出现次数的数组/对象,例如:

{1:1, 2:2:, 3:3, 4:1}

这是我目前所拥有的:

// sort first
arr.sort();

for (var i = 0, l = arr.length, i < l, i++) {
// what should go here ????
}

最佳答案

// Our results will be loaded into cont
var cont = {};

// For each number in our value array
for ( var i = 0; i < vals.length; i++ ) {
// If it's found in the result array
cont[ vals[i] ]
// Increment it
? cont[ vals[i] ]++
// Else, set it to 1
: cont[ vals[i] ] = 1 ;
}

可以使用 while 循环和变量赋值变得更简单:

var vals = [1, 2, 2, 3, 3, 3, 4], // Values to cycle through
cont = {}, // Object to store results in
indx = i = -1; // Index and Counting variables

while ( indx = vals[ ++i ] ) // While a value exists for location i
cont[ indx ] // Check to see if it's in the result object
? cont[ indx ]++ // If it is, increment it
: cont[ indx ] = 1 ; // If it is not, set it to 1

关于javascript - JS : Get number of same values,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10621988/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com