小编典典

如何计算数组中每个项目的出现次数?[重复]

javascript

我有一个数组如下

var arr = ['ab','pq','mn','ab','mn','ab']

预期结果

arr['ab'] = 3
arr['pq'] = 1
arr['mn'] = 2

尝试如下

$.each(arr, function (index, value) {
    if (value) 
        arr[value] = (resultSummary[value]) ? arr[value] + 1 : 1;
});

console.log(arr.join(','));

阅读 295

收藏
2020-05-01

共1个答案

小编典典

无需使用jQuery即可完成此任务-此示例将构建一个对象,其中包含数组中每个不同元素的出现次数 O(n)

var occurrences = { };
for (var i = 0, j = arr.length; i < j; i++) {
   occurrences[arr[i]] = (occurrences[arr[i]] || 0) + 1;
}

console.log(occurrences);        // {ab: 3, pq: 1, mn: 2}
console.log(occurrences['mn']);  // 2

var occurrences = arr.reduce(function(obj, item) {
  obj[item] = (obj[item] || 0) + 1;
  return obj;
}, {});

console.log(occurrences);        // {ab: 3, pq: 1, mn: 2}
console.log(occurrences['mn']);  // 2
2020-05-01