-1

I have a array like this:

[
  {
    id: 12,
    selected: true
  },
  {
    id: 12,
    selected: true
  }
]

I want only remove one of the same ID, but filter remove all, how can I only remove one object?

universe11
  • 703
  • 1
  • 11
  • 35
  • so you want to remove duplicates? https://stackoverflow.com/questions/2218999/how-to-remove-all-duplicates-from-an-array-of-objects – cmgchess Jul 09 '22 at 19:22
  • 1
    @cmgchess not only duplicates, maybe I have 5 of the same object I want only remove one – universe11 Jul 09 '22 at 19:26
  • What happens if the second duplicate has `selected: false`? Which object do you keep out the two? The first one in the iteration? – Andy Jul 09 '22 at 19:34

1 Answers1

1

To remove one object out of all duplicates you could use this:

let objectIds = {};
[
  {
    id: 12,
    selected: true
  },
    ,
  {
    id: 14,
    selected: true
  },
  {
    id: 12,
    selected: true
  },
  {
    id: 12,
    selected: true
  },
  {
    id: 14,
    selected: true
  }
].filter((obj) => {
    const oid = objectIds[obj.id];
    if ( oid ) {
        oid.nr += 1;
    } else {
        return objectIds[obj.id] = {nr: 1};
    }
    if (oid.nr > 1 && !oid.removed) {
        oid.removed = true;
        return false;
    }
    return true;
});
Rainer Plumer
  • 3,693
  • 2
  • 24
  • 42