-1

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];```
MrRagn
  • 7
  • 1
  • Welcome to SO! What does "something shorter" mean? Number of lines of code? Computational complexity? Also, what did you try and what was the problem? Post a [minimal reproducible example](https://stackoverflow.com/help/minimal-reproducible-example) – DCTID Mar 04 '20 at 02:56

1 Answers1

2

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();
Mohammad Niazmand
  • 1,509
  • 9
  • 13