Skip to content Skip to sidebar Skip to footer

Using Reduce And It Caused An Error That Says "cannot Read Property 'others' Of Undefined"

I'm using a reduce on this and it has an error that says: ''Cannot read property 'others' of undefined' This is the codesandbox link: https://codesandbox.io/s/filter-sr3ci?file=/sr

Solution 1:

It's because the object with the display name Person6 doesn't have a "1" object

When the Array.reduce function goes item by item, it could not find the "1" result in an undefined error.

So you just need to use optional chaining for it like so:

let red = others1.reduce(
  (a, c) => ((a[c["1"]?.others] = (a[c["1"]?.others] || 0) + 1), a),
  {}
);

Also, remove those dots before .["1"], since they are not valid, ['value'] is already equal to .value

Post a Comment for "Using Reduce And It Caused An Error That Says "cannot Read Property 'others' Of Undefined""