Borislav Hadzhiev
Sun Nov 14 2021·2 min read
Photo by Stefan Spassov
To count the duplicates in an array, declare an empty object variable that
will store the count for each value and use the forEach()
method to iterate
over the array. On each iteration, increment the count for the value by 1
or
initialize it to 1
if it hasn't been set already.
const arr = ['one', 'two', 'one', 'one', 'two', 'three']; const count = {}; arr.forEach(element => { count[element] = (count[element] || 0) + 1; }); // 👇️ {one: 3, two: 2, three: 1} console.log(count);
The function we passed to the Array.forEach method gets called with each element in the array.
For each element we check if the value in already present as a key in the
count
object. If it is present, we increment it by 1
.
If the value is not yet present, we initialize it to 1
.
undefined
, we initialize the value for the key to 0
+ 1
.After the last iteration, the count
object contains the values of the array as
keys pointing to their number of occurrences in the array.
An alternative approach, which helps us avoid the intermediary count
variable
is to use the
Array.reduce
method.
Use the reduce()
method to count the duplicates in an array, passing it an
empty object as the initial value for the accumulator. On each iteration,
increment the occurrences of present values in the object or initialize the
value to 1
.
const arr = ['one', 'two', 'one', 'one', 'two', 'three']; const count = arr.reduce((accumulator, value) => { return {...accumulator, [value]: (accumulator[value] || 0) + 1}; }, {}); // 👇️ {one: 3, two: 2, three: 1} console.log(count);
This approach is very similar to the previous one, however it allows us to avoid declaring an empty object variable.
The function we passed to the reduce()
method gets called for each element in
the array.
accumulator
variable.Whatever we return from the callback function, gets passed as the accumulator for the next iteration.
We use
destructuring assignment
to unpack the key-value pairs from the accumulator into a new object and
override the current property, by incrementing it or initializing it to 1
.
After the last iteration, the object stores the values of the array as keys and their occurrences in the array as values.