Important edit : I can't use filter
- the purpose is pedagogic.
I have an array in which I would want to count the number of its elements that verify a boolean, using only map
and reduce
.
Count of the array's size
I already wrote something that counts the array's size (ie. : the number of all of its elements), using reduce
:
const array_numbers = [12, 15, 1, 1]; // Size : 4
console.log(
array_numbers.reduce((acc) => {
return acc + 1;
}, 0)
);
Count of the array's elements checking a boolean condition
Now I would want to count only the elements that verify a boolean condition. Thus, I must use map
before reduce
and the elements of the map
's returned array will be only the good elements.
So I wrote this code but it doesn't work... Indeed, I put null
when I encounter a not-good element (and null
is counted as en element unfortunately).
NB : here, the boolean condition is "is the element even ? (%2 == 0)".
const array_numbers = [12, 15, 1, 1]; // Size : 4
console.log(
array_numbers.map((current_value) => {
if(current_value % 2 == 0) {
return current_value;
}
return null;
}).reduce((acc) => {
return acc + 1;
}, 0)
);