Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

why reduce accumulator doesn't return the intended sum result?

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());

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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());
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading