2
var array = [{id :1, name :"test1"},{id :2, name :"test2"},{id :2, name :"test2"},{id :3, name :"test3"},{id :4, name :"test4"}];

var anotherOne = [{id :2, name :"test2"}, {id :4, name :"test4"}];

var filteredArray  = array.filter(function(array_el){
   return anotherOne.filter(function(anotherOne_el){
      return anotherOne_el.id == array_el.id;
   }).length == 0
});

This code remove all "id:2" object. Like do this:

{id :1, name :"test1"},{id :3, name :"test3"}

But I want remove only one of same object. Like this:

{id :1, name :"test1"},{id :2, name :"test2"},{id :3, name :"test3"}

But If anotherOne of array have two same object, need two remove.

1 Answers1

5

You can try this: I am solving this using reduce and findIndex.

var array = [{id :1, name :"test1"},{id :2, name :"test2"},{id :2, name :"test2"},{id :3, name :"test3"},{id :4, name :"test4"}];
var anotherOne = [{id :2, name :"test2"}, {id :4, name :"test4"}];

const res = array.reduce((a, c) => {
    const index = anotherOne.findIndex(item => item.id === c.id);
 
    if (index > -1) {
       /**
        * Remove the matched one from the `anotherOne` array,
        * So that you don't have to match it second time.
        * So it removes the match one once.
        */
        anotherOne.splice(index, 1);
    } else {
        a.push(c);
    }

    return a;
}, []);

console.log(res);
.as-console-wrapper {min-height: 100%!important; top: 0;}
Sajeeb Ahamed
  • 6,070
  • 2
  • 21
  • 30