OneCompiler

[JavaScript] How to find the total number of occurrences of an element in an array?

I want to find how many times a given element present in an array, how can I do that in Javascript?

1 Answer

4 years ago by

Below is one of the simplest and concise way to find the total number of occurences of an element present in an array

let arr = [1, 22, 35, 22, 1 , 5, 22, 1, 5];

let numberOfOccurences = (number) => arr.reduce((ele, value) => (value === number ? ele+1 : ele), 0);
console.log(numberOfOccurences(5)); // outputs 2

Run the code here https://onecompiler.com/javascript/3xnkfvx8g

4 years ago by Meera