Last updated: Mar 2, 2024
Reading timeยท7 min
reduce()
forEach()
filter()
for
loopTo count the occurrences of each element in an array:
for...of
loop to iterate over the array.1
.// โ Count occurrences of each element in an array 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} console.log(count.a); // ๐๏ธ 3 console.log(count.b); // ๐๏ธ 1
The same approach can be used if you only need to count the occurrences of a specific element in the array.
// โ Count occurrences of a specific element in an array const arr = ['a', 'b', 'a', 'a']; let count = 0; for (const element of arr) { if (element === 'a') { count += 1; } } console.log(count); // ๐๏ธ 3
We declared a new variable and set it to an empty object.
The for...of loop allows us to iterate over the array.
if
condition checks if the current array element is present as a key in the object.If the element is present in the object, we increment the corresponding value,
otherwise, we initialize the key to 1
.
The keys in the object are the array elements and the values are the occurrences of each element in the array.
This approach also works if your array consists of numbers.
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
You can also use the Array.reduce()
method.
reduce()
This is a three-step process:
Array.reduce()
method to iterate over the array.1
or initialize it to
1
.const arr = ['b', 'a', 'c', 'b', 'b', 'a']; const count = arr.reduce((accumulator, value) => { accumulator[value] = ++accumulator[value] || 1; return accumulator; }, {}); console.log(count); // ๐๏ธ { b: 3, a: 2, c: 1 } console.log(count.a); // ๐๏ธ 2 console.log(count.b); // ๐๏ธ 3 console.log(count.c); // ๐๏ธ 1
The function we passed to the Array.reduce() method gets called for each element in the array.
accumulator
variable as an empty object because that's what we passed as the second argument to the reduce()
method.On each iteration, we check if the current array element exists as a key in the object.
If the key exists, we increment its value by 1
, otherwise, we initialize the
key to 1
.
You can also use a Map
object instead of a regular object.
const arr = ['b', 'a', 'c', 'b', 'b', 'a']; const count = arr.reduce((accumulator, value) => { accumulator.set(value, (accumulator.get(value) || 0) + 1); return accumulator; }, new Map()); // ๐๏ธ Map(3) { 'b' => 3, 'a' => 2, 'c' => 1 } console.log(count); console.log(count.get('a')); // ๐๏ธ 2 console.log(count.get('b')); // ๐๏ธ 3 console.log(count.get('c')); // ๐๏ธ 1 // ๐๏ธ [ 'b', 'a', 'c' ] console.log([...count.keys()]); // ๐๏ธ [ 3, 2, 1 ] console.log([...count.values()]); // ๐๏ธ [ [ 'b', 3 ], [ 'a', 2 ], [ 'c', 1 ] ] console.log([...count.entries()]);
We passed a Map
object as the second argument to the reduce()
function
instead of a regular object.
On each iteration, we set the current element as a key in the Map
and
increment its value or initialize it to 1
.
Map.get()
method to get the number of occurrences of each element in the array.The Map.keys()
method returns the array elements and the Map.values()
method
returns the number of occurrences of each element in the array.
The Map.entries()
method returns a two-dimensional array where the first
element is the array value and the second element is the number of times the
value is contained in the array.
If you have to do this often, define a reusable function.
function occurrencesOfEach(array) { const occurrences = array.reduce((accumulator, value) => { accumulator[value] = ++accumulator[value] || 1; return accumulator; }, {}); return occurrences; } const arr = ['b', 'a', 'c', 'b', 'b', 'a']; const result = occurrencesOfEach(arr); console.log(result); // ๐๏ธ { b: 3, a: 2, c: 1 } console.log(result.a); // ๐๏ธ 2 console.log(result.b); // ๐๏ธ 3 console.log(result.c); // ๐๏ธ 1
The function takes an array as a parameter and returns an object that stores the number of occurrences of each element in the array.
You can also use the Array.forEach()
method.
forEach()
This is a four-step process:
forEach()
method to iterate over the array.1
.// โ count occurrences of each element in an array const arr = ['b', 'a', 'c', 'b', 'b', 'a']; const count = {}; arr.forEach(element => { if (count[element]) { count[element] += 1; } else { count[element] = 1; } }); // ๐๏ธ { b: 3, a: 2, c: 1 } console.log(count);
The same approach can be used if you need to count the occurrences of a specific element in an array.
// โ count occurrences of a specific element in an array const arr = ['a', 'b', 'a', 'a']; let count = 0; arr.forEach(element => { if (element === 'a') { count += 1; } }); console.log(count); // ๐๏ธ 3
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 element is contained as a key in the object.
If the condition is met, we increment the key's value, otherwise, we initialize
the value to 1
.
If you have to do this often, define a reusable function.
function occurrencesOfEach(array) { const count = {}; array.forEach(element => { if (count[element]) { count[element] += 1; } else { count[element] = 1; } }); return count; } const arr = ['b', 'a', 'c', 'b', 'b', 'a']; const result = occurrencesOfEach(arr); console.log(result); // ๐๏ธ { b: 3, a: 2, c: 1 } console.log(result.a); // ๐๏ธ 2 console.log(result.b); // ๐๏ธ 3 console.log(result.c); // ๐๏ธ 1
The function takes an array as a parameter and returns an object containing the count of occurrences of each of the array elements.
filter()
This is a three-step process:
Array.filter()
method to iterate over the array.length
property on the result.const arr = ['a', 'b', 'a', 'a']; const count = arr.filter(element => { return element === 'a'; }).length; console.log(count); // ๐๏ธ 3
The function we passed to the Array.filter() method gets called with each element in the array.
On each iteration, we check if the current element is equal to the specified value and return the result.
The filter()
method returns a new array containing only the values for which
the callback function returned a truthy value.
const arr = ['a', 'b', 'a', 'a']; // ๐๏ธ [ 'a', 'a', 'a' ] console.log( arr.filter(element => { return element === 'a'; }), );
The last step is to access the length
property on the array to get the number
of times the element appears in the array.
If you have to do this often, define a reusable function.
function countOccurrences(array, value) { return array.filter(element => { return element === value; }).length; } const arr = ['a', 'b', 'a', 'a']; console.log(countOccurrences(arr, 'a')); // ๐๏ธ 3 console.log(countOccurrences(arr, 'b')); // ๐๏ธ 1 console.log(countOccurrences(arr, 'c')); // ๐๏ธ 0
The function takes an array and a value as parameters and returns the number of times the value is contained in the array.
You can also use a basic for
loop to count the occurrences of each element in
an array.
for
loopThis is a four-step process:
for
loop to iterate over the array.1
.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 sample achieves the same result. However, we use a basic for
loop,
instead of the for...of
loop or the Array.forEach()
method.
You can learn more about the related topics by checking out the following tutorials: