Last updated: Mar 4, 2024
Reading timeยท4 min
To count the duplicates in an array:
forEach()
method to iterate over the array.1
or initialize it
to 1
.const arr = ['one', 'one', 'one', 'two', '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.
On each iteration, we check if the current value is already present as a key in
the count
object.
If the value is present, we increment it by 1
, otherwise, we initialize it to
1
.
We used the logical OR (||) operator to check if the key hasn't been initialized in the object.
If the accessor returns undefined
, we initialize the value for the key to
0
+ 1
.
After the last iteration, the count
object contains the elements of the array
as keys and the number of their occurrences as values.
An alternative approach that helps us avoid the intermediary count
variable is
to use the Array.reduce()
method.
Array.reduce()
This is a three-step process:
Array.reduce()
method to iterate over the array.accumulator
.1
.const arr = ['one', 'one', 'one', 'two', '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. However, it allows us to avoid declaring an empty object variable.
The function we passed to the Array.reduce() method gets called for each element in the array.
We initialized the accumulator
variable to an empty object because that's what
we passed as the second argument to the reduce()
method.
The value we return from the callback function gets passed as the accumulator
on the next iteration.
We used destructuring assignment to
unpack the key-value pairs from the accumulator
into a new object where we
override the current property by incrementing it or initializing it to 1
.
After the last iteration, the object stores the elements of the array as keys and their occurrences in the array as values.
map
and filter
You can also count the duplicates in an array by using the Array.map()
and
Array.filter()
methods.
const arr = ['one', 'one', 'one', 'two', 'two', 'three']; const uniqueElements = [...new Set(arr)]; const count = uniqueElements.map(element => [ element, arr.filter(el => el === element).length, ]); // ๐๏ธ [ [ 'one', 3 ], [ 'two', 2 ], [ 'three', 1 ] ] console.log(count);
We used the Set()
constructor to remove the duplicates from the array and
called the Array.map()
method on the array of unique elements.
The function we passed to the Array.map() method gets called with each element in the array.
The map()
method returns a new array containing the values returned from the
callback function.
On each iteration, we return an array where the first element is the actual array element and the second is its number of occurrences in the array.
The function we passed to the Array.filter() method gets called with each element in the array.
The filter()
method returns a new array that only contains the elements that
meet the condition.
On each iteration, we check if the current element is a duplicate.
The last step is to access the length
property on the array of duplicates to
get the count.
for...of
loopYou can also use a for...of
loop to count the duplicates in an array.
const arr = ['one', 'one', 'one', 'two', 'two', 'three']; const count = {}; for (const element of arr) { count[element] = (count[element] || 0) + 1; } // ๐๏ธ { one: 3, two: 2, three: 1 } console.log(count);
The for...of statement is
used to loop over iterable objects like arrays, strings, Map
, Set
and
NodeList
objects and generators
.
On each iteration, we check if the element exists as a key in the object and
increment it if it does, otherwise, we initialize it to 1
.
for
loopYou can also use a basic for
loop to count the duplicates in an array.
const arr = ['one', 'one', 'one', 'two', 'two', 'three']; const count = {}; for (let index = 0; index < arr.length; index++) { count[arr[index]] = (count[arr[index]] || 0) + 1; } // ๐๏ธ { one: 3, two: 2, three: 1 } console.log(count);
The syntax for a for
loop is quite verbose and we have to make use of the
index to access the current array element.
Which approach you pick is a matter of personal preference. I'd use the
Array.forEach()
method as I find it quite direct and intuitive.
You can learn more about the related topics by checking out the following tutorials: