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

1 Answer 1

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;
}, {});
Sign up to request clarification or add additional context in comments.

2 Comments

Changed to (!!accu[curr[0]]) but still getting the same error. Error is in the line with the code "push"
It must be (!accu[curr[0]]). I've adjusted the answer. Please see if it works now.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.