get most occurring elements in array JavaScript

戏子无情 提交于 2019-12-08 02:21:59

问题


I have an array that I want to get the most occurring elements,

First scenario

let arr1 = ['foo', 'foo', 'foo', 'bar', 'bar', 'bar', 'baz', 'baz']
let newArr = someFunc(arr1)

so in this case I want the new array to have the value

console.log(newArr) // ['foo', 'bar'] 

Because the value 'foo' and 'bar' was the most occurring element of the array

Second scenario

 let arr2 = ['foo', 'foo', 'foo', 'bar', 'baz']
 let newArr = someFunc(arr2)

so in this case I want the new array to have the value

console.log(newArr) // ['foo']

Because the value 'foo' was the most occurring element of the array

This is what I have tried and it will only get me one of the elements even if there are more than one element that occurs the same amount of times

newArr= arr.sort((a,b) =>
arr.filter(v => v===a).length
- arr.filter(v => v===b).length
).pop()

回答1:


You can count the items with reduce and find the maximum occurring count. Then you can filter any keys that have that count:

let arr = ['foo', 'foo', 'foo', 'bar', 'bar', 'bar', 'baz', 'baz'];

let counts = arr.reduce((a, c) => {
  a[c] = (a[c] || 0) + 1;
  return a;
}, {});
let maxCount = Math.max(...Object.values(counts));
let mostFrequent = Object.keys(counts).filter(k => counts[k] === maxCount);

console.log(mostFrequent);



回答2:


You can calculate the max for each of the values and only return those which match via grouping them with an Array.reduce:

const mostFrequent = data => data.reduce((r,c,i,a) => {
  r[c] = (r[c] || 0) + 1
  r.max = r[c] > r.max ? r[c] : r.max
  if(i == a.length-1) {
    r = Object.entries(r).filter(([k,v]) => v == r.max && k != 'max')
    return r.map(x => x[0])
  }
  return r
}, {max: 0})

console.log(mostFrequent(['foo', 'foo', 'foo', 'bar', 'bar', 'bar', 'baz', 'baz']))
console.log(mostFrequent(['foo', 'foo', 'foo', 'bar', 'baz']))


来源:https://stackoverflow.com/questions/53509971/get-most-occurring-elements-in-array-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!