Encodera

Thanks for reading!

Donate to the site — we work hard for you.

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:

2

With 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: 1

Common 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:

NaN

Functions used in this recipe

Thanks for reading!

Donate to the site — we work hard for you.