0

I'm getting this error. Kindly note splits is an array with values.

TypeError: Cannot read property 'push' of undefined

on

var products = splits.reduce((accu, curr) => {
  if (accu[curr[0]] === null) {
    accu[curr[0]] = [];
  }
  accu[curr[0]].push(curr[1]);
  return accu;
}, {});

var result = Object.keys(products).map(key => `${key} - ${products[key].join(', ')}.`).join(' ');

Appreciate anyone helps to fix the above code

vdvaart
  • 15
  • 2

1 Answers1

1

null === undefined is false in Javascript.

console.log(null === undefined);

So the condition accu[curr[0]] === null will return false though the accu[curr[0]] is undefined. Instead you could use the negation (!) to check if the variable is defined

console.log(!null);
console.log(!undefined);

Try the following

let products = splits.reduce((accu, curr) => {
  if (!accu[curr[0]]) {
    accu[curr[0]] = [];
  }
  accu[curr[0]].push(curr[1]);
  return accu;
}, {});
Michael D
  • 20,838
  • 4
  • 12
  • 37