To find out how many times an element appears in an array in JavaScript, you can use the Array.filter()
method to create a new array containing only the elements that match the target element, and then get its length.
Here’s an example:
function countElements(array, target) {
return array.filter(element => element === target).length;
}
const array = [3, 7, 1, 2, 8, 4, 5, 3, 3];
console.log(countElements(array, 3)); // 3
In this example, we create a function countElements
that takes an array
and a target
as arguments. The function uses the Array.filter()
method to create a new array containing only the elements that match the target. Finally, it returns the length of the filtered array, which represents the number of times the target element appears in the original array.
+ There are no comments
Add yours