To get the count of elements in an array based on a specific value in JavaScript, you can use the reduce()
method along with an if statement to check if each element matches the specified value.
Here's an example of how to get the count of elements in an array that are equal to 5
:
javascriptconst arr = [1, 5, 3, 5, 2, 5, 4];
const count = arr.reduce((acc, val) => {
if (val === 5) {
return acc + 1;
} else {
return acc;
}
}, 0);
console.log(count); // Output: 3
In this example, the reduce()
method is used to iterate through each element of the arr
array and accumulate a count of elements that are equal to 5
.
The reduce()
method takes two arguments: a callback function and an initial value for the accumulator. The callback function takes two arguments: an accumulator (acc
) and the current value of the element being processed (val
).
The if statement in the callback function checks if the current value (val
) is equal to 5
. If it is, then the accumulator (acc
) is incremented by 1
. If it is not, the accumulator remains unchanged.
The initial value for the accumulator is 0
, so the reduce()
method initializes the acc
variable to 0
before iterating through the array.
The resulting count
variable contains the total count of elements in the array that are equal to 5
, and the output of the console.log()
statement is 3
.
JavaScript Interview Questions and Answers, JavaScript, JavaScript Tutorial
Comments
Post a Comment