最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

get most occurring elements in array JavaScript - Stack Overflow

programmeradmin2浏览0评论

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()

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()
Share Improve this question edited Nov 28, 2018 at 0:16 McKHAANNN asked Nov 27, 2018 at 23:45 McKHAANNNMcKHAANNN 1421 gold badge2 silver badges10 bronze badges 11
  • 2 How do you define "most frequent"? More than 2 occurrences or top n? What code have you tried that you're stuck on? – ggorlen Commented Nov 27, 2018 at 23:47
  • 1 Show us your attempt to implement it – Eriks Klotins Commented Nov 27, 2018 at 23:48
  • I mean that i want the top n of the array, it can be a single element or more if multiple element is n @gg – McKHAANNN Commented Nov 27, 2018 at 23:50
  • 1 Your question is unclear. 1) Please paraphrase your question to define what is your definition for "frequent elements" | 2) Show us what you've tried. – TechnoCorner Commented Nov 27, 2018 at 23:52
  • 1 if you just need a concept: throw the elements as keys into an object and increase their respectable value by one on each collision – GottZ Commented Nov 27, 2018 at 23:53
 |  Show 6 more ments

3 Answers 3

Reset to default 13

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);

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']))

You can also use a for ofloop and ìn

For example

const arrayFrecuent = [3, 1, 2, 1, 3, 2, 5, 4, 2, 10];

const mostFrecuent = givenArray => {
  let counts = {};
  let maxValue = -1;
  let maxItem = null;
  for (const num of givenArray) {
    if (!(num in counts)) {
      counts[num] = 1;
    } else {
      counts[num] = counts[num] + 1;
    }
    if (counts[num] > maxValue) {
      maxValue = counts[num];
      maxItem = num;
    }
  }
  return maxItem;
};

const mostFrecuentNumber = mostFrecuent(arrayFrecuent);

console.log("mostFrecuentNumber", mostFrecuentNumber);
发布评论

评论列表(0)

  1. 暂无评论