Answer the question
In order to leave comments, you need to log in
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
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]
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)
})
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question