M
M
mletov2018-06-07 07:13:56
JavaScript
mletov, 2018-06-07 07:13:56

How to find the elements that occur in an array the maximum number of times?

Please tell me.
I write in TypeScript.
There is an array of the form
[1,1,1,1,1, 3,3,3,3,3, 5,5 ,6,6,6, 7,7,7,7,7]
Get it is necessary
[1,3,7]
These are the elements that occur the maximum number of times.
Yes, I know how to solve this problem stupidly in the forehead, heaping up intermediate arrays and cycles.
But any beautiful and and effective decision interests. Like, for example, in sql or linq, something like group by, count, max, etc.

Answer the question

In order to leave comments, you need to log in

3 answer(s)
A
Anton Spirin, 2018-06-07
@mletov

const arr = [1,1,1,1,1, 3,3,3,3,3, 5,5 ,6,6,6, 7,7,7,7,7];

const map = {};
arr.forEach(el => map[el] = map[el] ? map[el] + 1 : 1);
const max = Math.max(...Object.values(map));
const result = Object.keys(map).filter(key => map[key] === max);

console.log(result); // [1 ,3, 7]

D
Dmitry Guryev, 2018-06-07
@djsv

Option with lodash:

const arr = [1,1,1,1,1, 3,3,3,3,3, 5,5 ,6,6,6, 7,7,7,7,7]
const items = _.countBy(arr) // {1: 5, 3: 5, 5: 2, 6: 3, 7: 5}
const max = _.max(_.toArray(items)) // 5
const result = []
_.forIn(items, (value, key) => {
  if (value === max) result.push(key)
})

W
webfln, 2018-06-07
@webfln

[1,1,1,1,1, 3,3,3,3,3, 5,5 ,6,6,6, 7,7,7,7,7].filter((v, i, a) => a.indexOf(v) === i);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question