To count the number of occurrences of a specified element in an array in JavaScript, you can use methods like reduce
, filter
, or loops to iterate through the array and count each occurrence.
In this example,
numbers
with values 10, 20, 30, 40, 30, 50.reduce
method to count the occurrences of element 30 in the array.reduce
method applies a function against an accumulator and each element in the array to reduce it to a single value.const numbers = [10, 20, 30, 40, 30, 50];
const count = numbers.reduce((acc, curr) => curr === 30 ? acc + 1 : acc, 0);
console.log(`Number of occurrences of element 30: ${count}`);
Number of occurrences of element 30: 2
In this example,
fruits
with values 'apple', 'banana', 'cherry', 'banana'.filter
method to filter the elements that match 'banana'.const fruits = ['apple', 'banana', 'cherry', 'banana'];
const count = fruits.filter(fruit => fruit === 'banana').length;
console.log(`Number of occurrences of element 'banana': ${count}`);
Number of occurrences of element 'banana': 2
In this tutorial, we learned How to count the Number of Occurrences of Specified Element in the Array in JavaScript language with well detailed examples.