I'm trying to write a function that counts the occurrences of a specific element in an array, specified as a function argument.
Ex: for the array [5,7,12,5,3,3,5], the function countOccurrences(3) would return a value of 2.
Thank you in advance :)
I'm trying to write a function that counts the occurrences of a specific element in an array, specified as a function argument.
Ex: for the array [5,7,12,5,3,3,5], the function countOccurrences(3) would return a value of 2.
Thank you in advance :)
You can filter array and return length:
const arr = [5,7,12,5,3,3,5];
const occurences = (array, el) => {
return array.filter(a => a === el).length
}
const result = occurences(arr, 3);
console.log(result)
You could try the following:
const filter = (arr, val) => {
return arr.filter(item => item === val).length
}