且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-11-28 15:44:34

无需使用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




示例小提琴