EN
JavaScript - count occurrences of array elements
3
points
In this article, we would like to show you how to count occurrences of array elements using JavaScript.
Practical examples
Example 1
In this example, we create a reusable function that counts occurrences and stores them in the object.
// ONLINE-RUNNER:browser;
const countElements = (array) => {
const counts = {};
for (const element of array) {
const count = counts[element] ?? 0; // or: const count = counts[element] || 0;
counts[element] = count + 1;
}
return counts;
};
// Usage example:
const input = ['a', 'a', 'a', 'b', 'b', 'c'];
const counts = countElements(input);
for (const key in counts) {
console.log(key + ' ' + counts[key]);
}
Example 2
In this example, we create a reusable function that counts occurrences and stores them in the object. Keys in the object are acheved using keyGetter function which lets to use a composite keys (composed of multiple properties).
// ONLINE-RUNNER:browser;
const countElements = (array, keyGetter) => {
const counts = {};
for (const element of array) {
const key = keyGetter(element);
const count = counts[key] ?? 0; // or: const count = counts[key] ?? 0;
counts[key] = count + 1;
}
return counts;
};
// Usage example:
const input = [
{ x: 1, y: 1 },
{ x: 1, y: 1 },
{ x: 1, y: 2 },
{ x: 2, y: 2 },
{ x: 2, y: 2 }
];
const counts = countElements(input, (element) => '(' + element.x + ',' + element.y + ')');
for (const key in counts) {
console.log(key + ': ' + counts[key]);
}