Home > Enterprise >  js remove only one object with the same id
js remove only one object with the same id

Time:07-10

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?

CodePudding user response:

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;
});

CodePudding user response:

function UniqueIds(a, param){
    return a.filter(function(item, pos, array){
        return array.map(function(mapItem){ return mapItem[param]; }).indexOf(item[param]) === pos;
    })
}

console.log(UniqueIds(obj, 'id'));

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

  • Related