get most occurring elements in array JavaScript

前端 未结 3 1870
借酒劲吻你
借酒劲吻你 2021-01-14 14:27

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

First scenario

let arr1 = [\'foo\', \'foo\', \'foo\', \         


        
相关标签:
3条回答
  • 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);

    0 讨论(0)
  • 2021-01-14 15:16

    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 讨论(0)
  • 2021-01-14 15:17

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

    0 讨论(0)
提交回复
热议问题