How to count occurrences of values in an array
Short answer
Go through the array and increase the counter in an object for each value:
const fruits = ['apple', 'pear', 'apple', 'plum', 'apple', 'pear'];
const counts = {};
for (const fruit of fruits) {
counts[fruit] = (counts[fruit] ?? 0) + 1;
}
console.log(counts);Output:
{
"apple": 3,
"pear": 2,
"plum": 1
}One value
If you need the count of only one value, filter the array:
const fruits = ['apple', 'pear', 'apple', 'plum'];
console.log(fruits.filter((fruit) => fruit === 'apple').length);Output:
2With Map
Map keeps the order of first appearance and accepts any keys, including numbers and objects:
const rolls = [3, 6, 3, 1, 6, 3];
const counts = new Map();
for (const roll of rolls) {
counts.set(roll, (counts.get(roll) ?? 0) + 1);
}
console.log([...counts].map(([value, count]) => `${value}: ${count}`).join(', '));Output:
3: 3, 6: 2, 1: 1Common mistake
Without a starting value, counts[fruit] + 1 turns into undefined + 1, which is NaN:
const counts = {};
counts.apple = counts.apple + 1;
console.log(counts.apple);Output:
NaNFunctions used in this recipe
- Array.prototype.reduce — Reduces an array to a single value.
- Array.prototype.filter — Creates a new array from the elements that pass a test.
- Object.groupBy — Groups the elements of an array by a key.