Home > front end >  How can I use reduce to add indexValue of an array?
How can I use reduce to add indexValue of an array?

Time:09-30

const numberArray = [2, 23, 3, 4, 5, 6, 7, 8, 9, 10];

const added = numberArray.reduce((sum, indexValue, index, numberArray) => { 

        if(index === 0) {
            console.log(`${index} : ${indexValue}`);
        }else{
            return sum  = indexValue;
        }

    }, 0);

console.log(added);

CodePudding user response:

The function passed to reduce should always return something, specifically a value that can be used in the reduction calculation. Currently yours doesn't if index === 0. The default return value is undefined, and once you perform math on undefined you get NaN.

Return a value. For example, if you want to return 0:

const numberArray = [2, 23, 3, 4, 5, 6, 7, 8, 9, 10];

const added = numberArray.reduce((sum, indexValue, index, numberArray) => { 

        if(index === 0) {
            console.log(`${index} : ${indexValue}`);
            return 0; // <--- here
        }else{
            return sum  = indexValue;
        }

    }, 0);

console.log(added);

  • Related