Borislav Hadzhiev
Fri Oct 15 2021·2 min read
Photo by Joshua Sazon
To count the occurrences of each element in an array:
for...of
loop to iterate over the array.1
if it doesn't.const arr = ['a', 'b', 'a', 'a', 'c', 'c']; const count = {}; for (const element of arr) { if (count[element]) { count[element] += 1; } else { count[element] = 1; } } console.log(count); // 👉️ {a: 3, b: 1, c: 2}
We first declare a variable and set it to an empty object.
The for...of loop allows us to iterate over the array.
Our if
condition checks if we already encountered a specific array element and
initialized it on the object or not.
If it's the first time we encounter an array element, we set the element as
the object's key and initialize its value to 1
.
If we encounter the same element again, we increment the value of the corresponding key in the object.
The final result is an object, whose keys are the array elements and the values - their occurrences in the array.
const arr = [1, 1, 1, 2, 3, 3]; const count = {}; for (const element of arr) { if (count[element]) { count[element] += 1; } else { count[element] = 1; } } console.log(count); // 👉️ {1: 3, 2: 1, 3: 2}
This seems a bit confusing as object keys can only be of type string or symbol in JavaScript.
However, you can still access the object's keys either way.
console.log(count[1]); // 👉️ 3 console.log(count['1']); // 👉️ 3
If you try to access the key of the object using a number, it will automatically get converted to a string under the hood.
for...of
loop is not supported in Internet Explorer. If you have to support the browser use a basic for loop instead.// Supported in IE const arr = ['a', 'b', 'a', 'a', 'c', 'c']; const count = {}; for (let index = 0; index < arr.length; index++) { const element = arr[index]; if (count[element]) { count[element] += 1; } else { count[element] = 1; } } console.log(count); // 👉️ {a: 3, b: 1, c: 2}
This code snippet achieves the same goal, however we use a basic for loop,
instead of the for...of
loop.