How to Count Array Element Occurrences in JavaScript
- Object-based Approach to Count Occurrences of Array Elements in JavaScript
-
Use
array.prototype.reduce
to Count Occurrences of Array Elements in JavaScript - Use a Custom Function to Count Occurrences of Array Elements in JavaScript
- Use Lodash to Count Occurrences of Array Elements in JavaScript
This tutorial will teach you how to count the number of occurrences of elements in an array. We’ll show you how to do it with Objects, Array.prototype.reduce
, a custom function, and Lodash.
Object-based Approach to Count Occurrences of Array Elements in JavaScript
You can count the occurrences of an array of elements by creating an object. Afterward, you add the array elements to the object using a for...of
loop.
During the for...of
loop, you check if the element is already in the object; if so, you increment its value by one. Otherwise, it’s a new element that you are adding to the object.
The loop repeats until it has added all the elements of the array and their frequency to the object. This means the property in the object is an element from the array, and its value is the number of its occurrence.
As a result, you can check for element occurrences using object[property]
, where the property
is an array element added to the object
.
The result will be its occurrences in the array.
const myArray = [3, 2, 3, 3, 5, 6, 5, 5, 8, 4, 4, 7, 7, 7];
const counts = {};
for (const num of myArray) {
counts[num] = counts[num] ? counts[num] + 1 : 1;
}
console.log(
counts[2], counts[3], counts[4], counts[5], counts[6], counts[7],
counts[8]);
Output:
1 3 2 3 1 3 1
Use array.prototype.reduce
to Count Occurrences of Array Elements in JavaScript
Array.prototype.reduce
takes two arguments: a callback function and an initial value. When you set the initial value to an Object, you can set the properties of this object as the array elements.
So the property values will be the element’s number of occurrences. To achieve this, the first iteration of the callback function adds the array elements as properties of the object.
At the same time, it sets their values to one.
Therefore, subsequent iterations will check if a value exists for a property. If true, it’ll increment it by one.
Otherwise, it’s a new element, setting its value to one. In the end, the object will contain the array of elements and their values as key-value pairs.
let myArray =
[2, 2, 3, 5, 6, 2, 1, 1, 1, 4, 5,
6].reduce(function(accumulator, currentValue) {
return accumulator[currentValue] ? ++accumulator[currentValue] :
accumulator[currentValue] = 1,
accumulator
}, {});
console.log(myArray);
Output:
Object { 1: 3, 2: 3, 3: 1, 4: 1, 5: 2, 6: 2 }
Use a Custom Function to Count Occurrences of Array Elements in JavaScript
You can implement a custom function that will take an array as an argument and return two arrays. The first will contain unique elements of the array that you passed as an argument to the function.
While the second will contain the number of occurrences for the elements.
Here is the function algorithm that counts the number of occurrences of array elements.
- Initialize two empty arrays called
A
andB
. - Set up a variable to keep track of a previous element when looping through the array.
- Clone the array that the function receives as an argument.
- Sort the cloned array.
- Loop through the cloned array with a
for...of
loop.
5.1 If the array element is not equal to the previous element.
5.1.1 Push the element into arrayA
.
5.1.2 Push an initial value of one into arrayB
.
5.2 Else
5.2.1 Increment the value in arrayB
.
5.2.2 Set the previous element to the current element. - Return array
A
and arrayB
.
The following code is the implementation of this algorithm.
let mArray = [2, 3, 4, 1, 2, 2, 5, 3, 7, 8, 1, 1, 6];
function countOccurrences(array) {
let arrayElements = [], occurrences = [], cloneOriginalArray = [...array],
previousElement;
// Sort the cloned array
cloneOriginalArray.sort();
for (let element of cloneOriginalArray) {
if (element !== previousElement) { // That means it's a new element
arrayElements.push(element); // push it into the array
occurrences.push(1); // push its occurence in the occurrence array
} else
++occurrences[occurrences.length - 1]; // Not a new element, so increment
// its occurrence
previousElement = element;
}
return [arrayElements, occurrences];
}
const arrayAndItsOccurrences = countOccurrences(mArray);
console.log(
'[' + arrayAndItsOccurrences[0] + ']',
'[' + arrayAndItsOccurrences[1] + ']');
Output:
[1,2,3,4,5,6,7,8] [3,3,2,1,1,1,1,1]
Use Lodash to Count Occurrences of Array Elements in JavaScript
Lodash has the .countBy
method that takes an array and returns an object. This object contains the elements in the array and their values as key-value pairs.
<body>
<script
src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.js"
integrity="sha512-WFN04846sdKMIP5LKNphMaWzU7YpMyCU245etK3g/2ARYbPK9Ub18eG+ljU96qKRCWh+quCY7yefSmlkQw1ANQ==" crossorigin="anonymous"
referrerpolicy="no-referrer"
>
</script>
<script>
let loArray = [2,2,3,3,1,1,5,3,4,4,8,3,2,9];
let lodash = _;
let occurrences = _.countBy(loArray);
console.log(occurrences)
</script>
</body>
Output:
Object { 1: 2, 2: 3, 3: 4, 4: 2, 5: 1, 8: 1, 9: 1 }
Habdul Hazeez is a technical writer with amazing research skills. He can connect the dots, and make sense of data that are scattered across different media.
LinkedInRelated Article - JavaScript Array
- How to Check if Array Contains Value in JavaScript
- How to Create Array of Specific Length in JavaScript
- How to Convert Array to String in JavaScript
- How to Remove First Element From an Array in JavaScript
- How to Search Objects From an Array in JavaScript
- How to Convert Arguments to an Array in JavaScript