-3

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>
vishnu
  • 13
  • 1
  • 5

1 Answers1

0

Count the total of individual elements using an object. Sort it based on repetency and return the second element in array

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])
ellipsis
  • 12,049
  • 2
  • 17
  • 33
  • 2
    Just a personal thought: We should not encourage answers on questions with poor quality, no research effort and most likely duplicates of existing ones. – briosheje Sep 27 '19 at 10:22
  • I have added the code which I worked on, it was too complex thats the reason I asked the question. Thanks – vishnu Sep 27 '19 at 10:43