r/JavaScriptTips • u/[deleted] • Apr 08 '23
5 Ways to Count Number of Occurrences in JavaScript Array
If you're working with arrays in JavaScript, you might find yourself needing to count the number of times a certain element appears in the array. Fortunately, JavaScript provides an easy and efficient way to do this with just a few lines of code.
To count the number of occurrences of an element in a JavaScript array, we can use the reduce() method. The reduce() method is used to apply a function to each element in an array and reduce the array to a single value.
Here's an example code snippet that demonstrates how to use reduce()
to count the number of occurrences of each element in an array:
const arr = ['apple', 'banana', 'apple', 'cherry', 'banana', 'apple'];
const countOccurrences = arr.reduce((acc, curr) => {
acc[curr] = acc[curr] ? acc[curr] + 1 : 1;
return acc;
}, {});
console.log(countOccurrences);In this code, we first define an array arr with some elements. Then, we use the reduce() method to count the number of occurrences of each element in the array.
The reduce() method takes a callback function that is called for each element in the array. In the callback function, we first check if the current element already exists in the accumulator object (acc), and if so, we increment its count by 1. Otherwise, we set its count to 1.
Finally, the reduce() method returns the accumulator object with the counts for each element. In this example, the output will be:
{ apple: 3, banana: 2, cherry: 1 }By using reduce() to count the occurrences of elements in an array, we can efficiently and easily handle this common programming task in JavaScript. Whether you're working with small or large arrays, this method can help you quickly and accurately count the number of times each element appears.
Learn other ways to Count Number of Occurrences in Array