How to find most common number in array using link in JavaScript?

86 Views Asked by At

I want find most common element in array using link in JavaScript. I have solution with loop, and it works good, but I need something shorter. I tried do solution with orderBy, count, key, orderByDescending link methods, but it not work. Any ideas? This is my array.

// Most common element is 9 (x5).
const array1 = [1, 6, 5, 3, 9, 3, 2, 5, 4, 1, 6, 8, 4, 2, 1, 9, 10, 2, 5, 11, 21, 3, 1, 9, 4, 9, 3, 0, 9];```
1

There are 1 best solutions below

0
Mohammad Niazmand On

I think this would be the shortest:

var mostFrequentNumber = from([
      1,
      6,
      5,
      3,
      9,
      3,
      2,
      5,
      4,
      1,
      6,
      8,
      4,
      2,
      1,
      9,
      10,
      2,
      5,
      11,
      21,
      3,
      1,
      9,
      4,
      9,
      3,
      0,
      9,
    ]).groupBy(x => x).orderByDescending(x => x.count()).first().key();