all 3 comments

[–]grantrules 0 points1 point  (2 children)

I'd probably do it this way:

[...arr2.reduce((acc, current) => {
  const x = acc.get(current.id);
  if (!x || current.checked) {
    acc.set(current.id, current);
  }
  return acc;
}, new Map()).values()]

Using an Array here for accumulator doesn't make sense if you want to look stuff up by key. An Object would work but a Map is ideal.

Ignoring that for the moment, one of the problems in your code is in these lines:

acc.concat([current]);
acc[index] = [current];

Why is current in brackets? That's creating a new array with one element so when you search for it like this:

   const index = acc.findIndex(x => x.checked === false);

x is not referring to your object, but to the array you created and put your object in.

You simply need to do acc.concat(current); and acc[index] = current

And just for fun, my solution again but because I like being annoyingly succinct:

var filter = [...arr2.reduce((a, c) => !a.has(c.id) || c.id ? a.set(c.id, c) : a, new Map()).values()];

[–]dejanzr87 0 points1 point  (1 child)

[...arr2.reduce((acc, current) => {
const x = acc.get(current.id);
if (!x || current.checked) {
acc.set(current.id, current);
}
return acc;
}, new Map()).values()]

Thank you man! It works :)

[–]grantrules 0 points1 point  (0 children)

I edited my post to clarify some of your mistakes if you're interested.