如何找到数组中第二高频率的元素?我发现最频繁的元素pls修改没有任何循环

时间:2019-09-27 10:14:09

标签: javascript

我正在寻找一种优雅的方法来确定JavaScript数组中哪个元素的出现次数第二高。

例如,在

array = [4,5,6,2,1,3,3,5,3,7,3,9,2,2]

输出:2(最多出现的是“ 3”计数为4,第二最多出现的是“ 2”计数为3)

<html>
<body>
<script>
var array= '45621335373922'
var b =[];
b=array.split('');// convert to array
console.log(b);//["4", "5", "6", "2", "1", "3", "3", "5", "3", "7", "3", "9", "2", "2"]
// find most frequent number
let max = 0, letter;
for (let i = 0; i < array.length; i++ ) {
  let count = 0;
for (let j = 0; j < array.length; j++ ) {
  if (array[i] === array[j]) {
  ++count;
  }
}
if (max < count) { max = count; letter = array[i] }
}

console.log(letter + ' : ' + max + ' times' );
//remove most frequent number
for (let i=0; i<max;i++) 
  {
    var index = b.indexOf(letter);
    if (index > -1) {
       b.splice(index, 1);
    }
  }
console.log(b);
//find second most frequent number
let max1 = 0, letter1;
for (let i = 0; i < b.length; i++ ) {
let count1 = 0;
for (let j = 0; j < b.length; j++ ) {
if (b[i] === b[j]) {
  ++count1;
  }
}
if (max1 < count1) { max1 = count1; letter1 = b[i] }
}
console.log(letter1 + ' : ' + max1 + ' times' );
</script>
</body>
</html>

1 个答案:

答案 0 :(得分:0)

使用一个对象计算单个元素的总数。根据重复性对其进行排序,并返回数组中的第二个元素

var array = [4,5,6,2,1,3,3,5,3,7,3,9,2,2]
var obj={};
array.forEach(function(e){
if(obj.hasOwnProperty(e))
obj[e]++;
else
obj[e]=1;
})
console.log(Object.keys(obj).sort(function(a,b){return obj[b]-obj[a]})[1])