如何计算数组中每个项目的出现次数? [英] How to count the number of occurrences of each item in an array?
本文介绍了如何计算数组中每个项目的出现次数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个数组如下,
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(','));
推荐答案
无需使用jQuery执行此任务—这个例子将构建一个对象,其中包含数组中每个不同元素的出现量 O(n)
no need to use jQuery for this task — this example will build an object with the amount of occurencies of every different element in the array in 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
您还可以使用 Array.reduce 获得相同的结果并避免 for-loop
You could also use Array.reduce to obtain the same result and avoid a for-loop
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
这篇关于如何计算数组中每个项目的出现次数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文