I have an array of arrays (with boolean elements), say,
const array = [[false, false], [false, true], [true, true]];
And I want to use a reduce()
to count how many true there are, this is what I try:
const check = (array) => {
const numNotAnsweredQuestion = array.reduce((acc, elem1) => {
return (
acc +
elem1.reduce((acc2, elem2) => {
return elem2 ? acc2 + 1 : acc2;
}, 0)
);
}, 0);
return numNotAnsweredQuestion;
};
That is, I accumulate twice, or not?
The browser returns the function:
Your function works. It gives me the idea that you only need to invoke it. But ... it's bad practice to shadow variables/parameters. Better to use, inside the function, variables that are not called the same as those outside.
That said, the approach:
It's perfect. However you are operating on an array that you know and your implementation is a particular solution.
If instead you had an array that you only know has elements in nesting levels of depth N, and you wanted to count
truthy
(non-empty strings, true, non-zero numbers, objects) orfalsy
(empty strings, null, undefined, 0, false, NaN)You can use recursion to call the function
countTruthy
over any nested element that is an array, and maptruthy
to 1 andfalsy
0 otherwise:This approach works on your example array and in general on any array whose elements you can coerce to a boolean
I think the following should be considered:
reduce
reduce
to an element but not a matrix , given that it does not seem to me the correct way to want to implement itsample code
Passing it the function that checks if the value is true and in that case adding one to the accumulator should suffice:
However, you can do it in a simpler way using flat and filter:
I understand that the shortest and most efficient way is to do
.flat
and then.reduce
:The
false
will be 0 and thetrue
1. This is valid only if the values aretrue
orfalse
.