How to get the number of occurences of a value in an array in Javascript?
To get the number of occurrences of a value in an array in JavaScript, you can use the `reduce()
` method. The `reduce()` method applies a function to each element in an array to reduce the array to a single value. In this case, we can use `reduce()` to count the number of occurrences of a value in the array.
Here's an example code that demonstrates how to get the number of occurrences of a value in an array in JavaScript using the `reduce()` method:
const arr = [1, 2, 3, 2, 4, 2, 5];
const count = arr.reduce((acc, val) => val === 2 ? acc + 1 : acc, 0);
console.log(count); // Output: 3
In this example, we first create an array `arr` containing multiple occurrences of the value `2`. Then we use the `reduce()` method to count the number of occurrences of `2` in the array.
The `reduce()` method takes two arguments: a callback function and an initial value. In our example, the callback function takes two arguments: an accumulator (`acc`) and a current value (`val`). If the current value (`val`) is equal to `2`, we increment the accumulator by 1, otherwise we return the accumulator as is. We start with an initial value of `0`.
Finally, we log the `count` variable to the console, which contains the number of occurrences of `2` in the `arr` array. The output is `3`.