Reputation: 27
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
Upvotes: 0
Views: 60
Reputation: 31125
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;
}, {});
Upvotes: 1