I'm looking for an elegant way of determining which element has the second highest occurrence element in a JavaScript array.
For example, in
array = [4,5,6,2,1,3,3,5,3,7,3,9,2,2]
Output : 2 ( most occurring is '3' count is 4 and second most occurring is '2' count is 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>