假设我有这个数组:
[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 ????
}
假设我有这个数组:
[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
您正在寻找的是直方图:
http://jsfiddle.net/jbabey/jdMgp/
var array = [1, 2, 2, 3, 3, 3, 4];
var results = {};
for (var i = 0; i < array.length; i++) {
if (results.hasOwnProperty(array[i])) {
results[array[i]]++;
} else {
results[array[i]] = 1;
}
}
console.log(results);
无需排序。
var result = {};
for (var i = 0; i < arr.length; i++){
if (!result[arr[i]]) {
result[arr[i]]=0;
}
result[arr[i]]+=1;
}
干得好!
var arr = [1, 2, 2, 3, 3, 3, 4]; // Sample data
var countings = {}; // Result object
for (var i = 0; i < arr.length; i++) {
if(countings[(arr[i])] == undefined) countings[(arr[i])] = 0;
countings[(arr[i])]++;
}
您可以使用数组forEeach
方法:
var freq = {}, arr = [1, 2, 2, 3, 3, 3, 4];
arr.forEach(function(x){
freq[x] = freq[x] ? freq[x]+1 : 1;
});
//=> freq[1] = 1, freq[2] = 2, freq[3] = 3 and freq[4] = 1
//=> arr is still [1, 2, 2, 3, 3, 3, 4]