Sanket Shevkar
Sanket Shevkar

Reputation: 145

Accumulator of reduce function undefined if not returned. Why does it behave like this?

Array to be reduced:

const users = [
    { firstname: "Sanket", lastname: "Shevkar", age: 22 },
    { firstname: "Aniket", lastname: "Bhalla", age: 45 },
    { firstname: "Tanvi", lastname: "Shinde", age: 21 },
    { firstname: "Saif", lastname: "Siddiqi", age: 67 },
  ];
const outout = users.reduce((acc, curr)=>{
                     if(curr.age<45){
                        acc.push(curr.firstname);
                     }
                }, [])

Throws TypeError:

Uncaught TypeError: Cannot read property 'push' of undefined

I have passed an empty array to initialize the acc (accumulator), but still it throws typeError. If I return acc at the end, it works perfectly.

const outout = users.reduce((acc, curr)=>{
                     if(curr.age<45){
                        acc.push(curr.firstname);
                     }
                     return acc;
                }, [])

Can someone explain this behaviour?

Upvotes: 0

Views: 530

Answers (1)

Nikita Mazur
Nikita Mazur

Reputation: 1785

Array.reduce must return accumulator on every loop

const users = [
    { firstname: "Sanket", lastname: "Shevkar", age: 22 },
    { firstname: "Aniket", lastname: "Bhalla", age: 45 },
    { firstname: "Tanvi", lastname: "Shinde", age: 21 },
    { firstname: "Saif", lastname: "Siddiqi", age: 67 },
  ];
const outout = users.reduce((acc, curr)=>{
                     if(curr.age<45){
                        return acc.concat(curr.firstname);
                     }
                     return acc
                }, [])
                
                console.log(outout)

Upvotes: 2

Related Questions