如何计算数组中每个项目的出现次数?
问题描述:
我有一个数组如下,
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