获取数组中出现次数最多的项

问题描述 投票:0回答:14
var store = ['1','2','2','3','4'];

我想找出

2
在数组中出现次数最多的。我该怎么做呢?

javascript arrays algorithm search
14个回答
32
投票

我会做类似的事情:

var store = ['1','2','2','3','4'];
var frequency = {};  // array of frequency.
var max = 0;  // holds the max frequency.
var result;   // holds the max frequency element.
for(var v in store) {
        frequency[store[v]]=(frequency[store[v]] || 0)+1; // increment frequency.
        if(frequency[store[v]] > max) { // is this frequency > max so far ?
                max = frequency[store[v]];  // update max.
                result = store[v];          // update result.
        }
}

7
投票

解决方案,重点是

Array.prototype.forEach
,以及如果在更多项目之间共享最大计数,则获得多个密钥的问题。

编辑:只有一个循环的提案。

var store = ['1', '2', '2', '3', '4', '5', '5'],
    distribution = {},
    max = 0,
    result = [];

store.forEach(function (a) {
    distribution[a] = (distribution[a] || 0) + 1;
    if (distribution[a] > max) {
        max = distribution[a];
        result = [a];
        return;
    }
    if (distribution[a] === max) {
        result.push(a);
    }
});
console.log('max: ' + max);
console.log('key/s with max count: ' + JSON.stringify(result));
console.log(distribution);


5
投票
arr.sort();
    var max=0,result,freq = 0;
    for(var i=0; i < arr.length; i++){
        if(arr[i]===arr[i+1]){
            freq++;
        }
        else {
            freq=0;
        }
        if(freq>max){
            result = arr[i];
            max = freq;
        }
    }
    return result;

2
投票

制作一个直方图,找到直方图中最大数字的键。

var hist = [];
for (var i = 0; i < store.length; i++) {
  var n = store[i];
  if (hist[n] === undefined) hist[n] = 0;
  else hist[n]++;
}

var best_count = hist[store[0]];
var best = store[0];
for (var i = 0; i < store.length; i++) {
  if (hist[store[i]] > best_count) {
    best_count = hist[store[i]];
    best = store[i];
  }
}

alert(best + ' occurs the most at ' + best_count + ' occurrences');

这假设要么没有关系,要么你不关心选择哪一个。


2
投票

另一个 ES6 选项。适用于字符串或数字。

function mode(arr) {
  const store = {}
  arr.forEach((num) => store[num] ? store[num] += 1 : store[num] = 1)
  return Object.keys(store).sort((a, b) => store[b] - store[a])[0]
}

1
投票

如果数组已排序,这应该可以工作:

function popular(array) { 
   if (array.length == 0) return [null, 0];
   var n = max = 1, maxNum = array[0], pv, cv;

   for(var i = 0; i < array.length; i++, pv = array[i-1], cv = array[i]) {
      if (pv == cv) { 
        if (++n >= max) {
           max = n; maxNum = cv;
        }
      } else n = 1;
   }

   return [maxNum, max];
};

popular([1,2,2,3,4,9,9,9,9,1,1])
[9, 4]

popular([1,2,2,3,4,9,9,9,9,1,1,10,10,10,10,10])
[10, 5]

0
投票

当计数超过尚未计数的项目数时,此版本将停止查找。

无需对数组进行排序即可工作。

Array.prototype.most= function(){
    var L= this.length, freq= [], unique= [], 
    tem, max= 1, index, count;
    while(L>= max){
        tem= this[--L];
        if(unique.indexOf(tem)== -1){
            unique.push(tem);
            index= -1, count= 0;
            while((index= this.indexOf(tem, index+1))!= -1){
                ++count;
            }
            if(count> max){
                freq= [tem];
                max= count;
            }
            else if(count== max) freq.push(tem);
        }
    }
    return [freq, max];
}

    //test
    var A= ["apples","oranges","oranges","oranges","bananas",
   "bananas","oranges","bananas"];
    alert(A.most()) // [oranges,4]

    A.push("bananas");
    alert(A.most()) // [bananas,oranges,4]

0
投票

我用这种方法解决了它,以找到最常见的整数

function mostCommon(arr) {
    // finds the first most common integer, doesn't account for 2 equally common integers (a tie)

    freq = [];

    // set all frequency counts to 0
    for(i = 0; i < arr[arr.length-1]; i++) {
      freq[i] = 0;
    }

    // use index in freq to represent the number, and the value at the index represent the frequency count 
    for(i = 0; i < arr.length; i++) {
      freq[arr[i]]++; 
    }

    // find biggest number's index, that's the most frequent integer
    mostCommon = freq[0];
    for(i = 0; i < freq.length; i++) {
      if(freq[i] > mostCommon) {
        mostCommon = i;
      }
    }

    return mostCommon;
} 

0
投票

这是我的解决方案。

var max_frequent_elements = function(arr){
var a = [], b = [], prev;
arr.sort();
for ( var i = 0; i < arr.length; i++ ) {
    if ( arr[i] !== prev ) {
        a.push(arr[i]);
        b.push(1);
    } else {
        b[b.length-1]++;
    }
    prev = arr[i];
}


var max = b[0]
for(var p=1;p<b.length;p++){
       if(b[p]>max)max=b[p]
 }

var indices = []
for(var q=0;q<a.length;q++){
   if(b[q]==max){indices.push(a[q])}
}
return indices;

};


0
投票

以上所有解决方案都是迭代的。

这是 ES6 功能无突变版本:

Array.prototype.mostRepresented = function() {
  const indexedElements = this.reduce((result, element) => {
    return result.map(el => {
      return {
        value: el.value,
        count: el.count + (el.value === element ? 1 : 0),
      };
    }).concat(result.some(el => el.value === element) ? [] : {value: element, count: 1});
  }, []);
  return (indexedElements.slice(1).reduce(
    (result, indexedElement) => (indexedElement.count > result.count ? indexedElement : result),
    indexedElements[0]) || {}).value;
};

它可以在性能成为瓶颈的特定情况下进行优化,但它在处理任何类型的数组元素方面具有很大的优势。

最后一行可以替换为:

  return (indexedElements.maxBy(el => el.count) || {}).value;

与:

Array.prototype.maxBy = function(fn) {
  return this.slice(1).reduce((result, element) => (fn(element) > fn(result) ? element : result), this[0]);
};

为了清晰起见


0
投票

为什么有人应该对最常出现的项目感兴趣,而不是第二个或前 n 个最常出现的项目,或者最后 n 个出现的项目?

import { TrueSet } from "@ut8pia/classifier/queue/TrueSet.js";
import { Classifier } from "@ut8pia/classifier/queue/Classifier.js";
import assert from "assert";

const 
    data = ['1','2','2','3','4'],
    expected = 2;

在你的问题中,我看到两个隐含的问题:

  • 计算每个项目出现次数的最简单方法是什么?
const
    classifier = new Classifier()
        .letAll(data)
  • 如何根据这些事件对项目进行排序?
const
    repr = item => classifier.n(item)
    sorting = new TrueSet(repr)
        .letAll(data)

Classifier
维护每个存储项目的出现次数
n(item)
TrueSet
根据将每个项目与其出现次数相关联的表示
repr
函数对项目进行排序。

出现次数最多的项目可以轻松检索为排序中的最后一个项目

peek(false)

const
    got = sorting.peek(false);

assert.equal(got, expected)  

-1
投票

如果数组包含字符串,请尝试此解决方案

    function GetMaxFrequency (array) {
    var store = array;
    var frequency = [];  // array of frequency.
    var result;   // holds the max frequency element.

    for(var v in store) {
        var target = store[v];
        var numOccurences = $.grep(store, function (elem) {
        return elem === target;
        }).length;
        frequency.push(numOccurences);

    }
    maxValue = Math.max.apply(this, frequency);
    result = store[$.inArray(maxValue,frequency)];
    return result;
}
var store = ['ff','cc','cc','ff','ff','ff','ff','ff','ff','yahya','yahya','cc','yahya'];
alert(GetMaxFrequency(store));

-1
投票

一个相当简短的解决方案。

function mostCommon(list) {
  var keyCounts = {};
  var topCount = 0;
  var topKey = {};
  list.forEach(function(item, val) {
    keyCounts[item] = keyCounts[item] + 1 || 1;
    if (keyCounts[item] > topCount) {
      topKey = item;
      topCount = keyCounts[item];
    }
  });

  return topKey;
}

document.write(mostCommon(['AA', 'AA', 'AB', 'AC']))


-1
投票

此解决方案返回数组中出现次数最多的数字的数组,以防多个数字出现在“最大”次数。

    function mode(numbers) {
      var counterObj = {}; 
      var max = 0;
      var result = [];
      for(let num in numbers) {
        counterObj[numbers[num]] = (counterObj[numbers[num]] || 0) + 1; 
        if(counterObj[numbers[num]] >= max) { 
          max = counterObj[numbers[num]];
        }
      }
      for (let num in counterObj) {
        if(counterObj[num] == max) {
          result.push(parseInt(num));
        }
      }
      return result;
    }
© www.soinside.com 2019 - 2024. All rights reserved.