-2

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 :)

magniFITO
  • 3
  • 1
  • 3
    Does this answer your question? [Counting the occurrences / frequency of array elements](https://stackoverflow.com/questions/5667888/counting-the-occurrences-frequency-of-array-elements) – Harsh Gundecha Jul 30 '21 at 14:04
  • Please take the [tour] and read [ask], the first section of which is titled "Search, and research". This is a common question that has been asked hundreds of times before. – Heretic Monkey Jul 30 '21 at 14:04

2 Answers2

0

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)
Nikola Pavicevic
  • 21,952
  • 9
  • 25
  • 46
0

You could try the following:

const filter = (arr, val) => {
    return arr.filter(item => item === val).length
}
Krisztián Balla
  • 19,223
  • 13
  • 68
  • 84