我有javascript数组,在这个数组中,我需要返回3个发生率最高的值。假设我们有这样一个数组。
[1,3,4,5,2,3,4,5,6,7,8,5,4,5,3,5,6,7,3,5,6,5,6,3,4,5,6,6]1-1乘以2-1乘以3-5乘以4-4乘以5-8乘以6-6乘以7-2乘以8-1
如何使用jQuery返回3个出现次数最多的值(在本例中为4、5和6)。
希望这是合理的。
提前谢谢。
发布于 2016-11-18 01:56:25
var arr = [1,3,4,5,2,3,4,5,6,7,8,5,4,5,3,5,6,7,3,5,6,5,6,3,4,5,6,6];
var x = arr.reduce(function(result, item) {
result[item] = result[item] || {count:0};
++result[item].count;
return result;
}, {});
var y = Object.keys(x).sort(function(a, b) {
return x[b].count - x[a].count;
}).slice(0,3);
console.log(y);发布于 2016-11-18 04:47:52
var arr = [5, 5, 5, 2, 2, 2, 2, 2, 9, 4,1,1,2,1,1,1,3,3,3,3,3];
var counts = {};
for(var i = 0; i< arr.length; i++) {
var num = arr[i];
counts[num] = counts[num] ? counts[num]+1 : 1;
}
console.log(counts);// return object which return key value pair count like Object {2: 5, 4: 1, 5: 3, 9: 1} 2 five time,4 one time, 5 three time in array
var keysSorted = Object.keys(counts).sort(function(a,b){return counts[a]-counts[b]})
alert(keysSorted);
alert(keysSorted); //this is asc order, last 3 values are max occurance
https://stackoverflow.com/questions/40668016
复制相似问题