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.

3
  • 1
    also share your wanted result..for better idea Commented May 3, 2020 at 10:09
  • What is the rule of the anotherOne array here? Commented May 3, 2020 at 10:14
  • I want to subtract the second array from the first array. Commented May 3, 2020 at 10:17

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.