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.
In this example, we create a reusable function that counts occurrences and stores them in the object.
xxxxxxxxxx
1
const countElements = (array) => {
2
const counts = {};
3
for (const element of array) {
4
const count = counts[element] ?? 0; // or: const count = counts[element] || 0;
5
counts[element] = count + 1;
6
}
7
return counts;
8
};
9
10
11
// Usage example:
12
13
const input = ['a', 'a', 'a', 'b', 'b', 'c'];
14
const counts = countElements(input);
15
16
for (const key in counts) {
17
console.log(key + ' ' + counts[key]);
18
}
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).
xxxxxxxxxx
1
const countElements = (array, keyGetter) => {
2
const counts = {};
3
for (const element of array) {
4
const key = keyGetter(element);
5
const count = counts[key] ?? 0; // or: const count = counts[key] ?? 0;
6
counts[key] = count + 1;
7
}
8
return counts;
9
};
10
11
12
// Usage example:
13
14
const input = [
15
{ x: 1, y: 1 },
16
{ x: 1, y: 1 },
17
{ x: 1, y: 2 },
18
{ x: 2, y: 2 },
19
{ x: 2, y: 2 }
20
];
21
22
const counts = countElements(input, (element) => '(' + element.x + ',' + element.y + ')');
23
24
for (const key in counts) {
25
console.log(key + ': ' + counts[key]);
26
}