Home > Net >  .push() array method don't seem to be working on accumulator .reduce method
.push() array method don't seem to be working on accumulator .reduce method

Time:10-27

why is .push() method not working on an array in an accumulator object in .reduce() method

let a = [];
for (let i = 0; i <= 20; i  ) {
  a.push(i);
}

let {
  even,
  odd
} = a.reduce((acc, val) => {
  val % 2 === 0 ? acc.even.push(val) : acc.odd.push(val);
}, {
  even: [],
  odd: []
});

CodePudding user response:

Here's the OP function, returning the accumulator.

  let a = [];
  for (let i = 0; i <= 20; i  ) {
    a.push(i);
  }
  
  let result = a.reduce((acc, val) => {
    val % 2 === 0 ? acc.even.push(val) : acc.odd.push(val);
    return acc;
  }, { even: [], odd: [] });
  
  console.log(result)
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related