my goal : I want to understand why reduce isn’t working as I intended, not how to get the value I expected with other method
my expected results : I expect to have the acc evaluates to sum of 1 in the array but the result I have was 0. yet when I change the acc++ to console.log(item), all item pass the if condition and the value is 1, as expected.
function testReduce() {
let a = [1,1,1,1,1,1,1,1,1].reduce((acc, item) => item == 1 ? acc++ : acc,0)
return a;
}
console.log(testReduce());
>Solution :
Post-increment behavior: acc will be returned before it is incremented.
To avoid confusion, just return acc + 1:
function testReduce() {
let a = [1, 1, 1, 1, 1, 1, 1, 1, 1]
.reduce((acc, item) => item == 1 ? acc + 1 : acc, 0);
return a;
}
console.log(testReduce());