In an array we can store different elements, those elements can be integer, character, string or anything. And there could be repetition of elements in an array. This article discusses the method to find the number of occurrences of an element in the array. Number of occurrence means how many times the element occurred or appeared in the array.
To find the number of occurrences we have to write a correct function that can find it. The function required for this operation is only one line function.
- Create a function which takes an array and value of element as parameter.
- And write the mathematical expression for counting the number of occurrences of elements.
- now just pass the array and the element by console.log() function to find out the number of occurrences of the element in the array.
const countOccurrences = (arr, val) => arr.reduce((a, v) => (v === val ? a + 1 : a), 0);
console.log(countOccurrences([1, 1, 2, 1, 2, 3], 1));
console.log(countOccurrences([1, 1, 2, 1, 2, 3], 2));
console.log(countOccurrences([1, 1, 2, 1, 2, 3], 3));
In the above example we entered the array [1, 1, 2, 1, 2, 3] and we looked for the element ‘1’. The program completes its loop and shows the number of occurrences as 3, since it occurred 3 times in our array.
Hope this will help.