0

I have two arrays that contain objects. From first array how can I remove the items that are already present in the second array?

First array:

var s = [
  {"Name": "1"},
  {"Name": "2"},
  {"Name": "3"},
  {"Name": "4"},
  {"Name": "5"},
  {"Name": "6"}
]

Second array:

var t = [
  {"Name": "1"},
  {"Name": "2"},
  {"Name": "3"},
  {"Name": "8"}
]

Expected output:

[
  {"Name": "4"},
  {"Name": "5"},
  {"Name": "6"}
]
3
  • 1
    have you tried this yourself? Commented Jul 8, 2020 at 16:39
  • You need to understand compound data equality in JavaScript. See this Q&A for guidance Commented Jul 8, 2020 at 16:41
  • You can use filter() along with some() Commented Jul 8, 2020 at 16:42

3 Answers 3

1

You can use filter() along with some()

var s = [{"Name":"1"},{"Name":"2"},{"Name":"3"},{"Name":"4"},{"Name":"5"},{"Name":"6"}];
var t = [{"Name":"1"},{"Name":"2"},{"Name":"3"},{"Name":"8"}];

result = s.filter(a => !t.some(b => a.Name === b.Name));
console.log(result);

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

Comments

0

An approach using set and .filter method

var s=[
  {
    "Name": "1"
  },
  {
    "Name": "2"
  },
  {
    "Name": "3"
  },
  {
    "Name": "4"
  },
  {
    "Name": "5"
  },
  {
    "Name": "6"
  }
];

var t= [
  {
    "Name": "1"
  },
  {
    "Name": "2"
  },
  {
    "Name": "3"
  },{
    "Name": "8"
  }
];

var set = new Set();
t.forEach(obj => set.add(obj.Name));

s=s.filter(obj => !set.has(obj.Name))

console.log(s);

Comments

0
z = f(s, t);
function f(first, second) {
    var z = [];
    for (var i = 0; i < first.length; i++) {
      var included = false;
      for (let j = 0; j < second.length; j++) {
        if(equal(first[i], second[j]))  
          included = true;
          //break; //optional     
      }   
      if(!included)
        z.push(first[i]);   
    }

    return z;
}

function equal(a,b){
  //however you define the objs to be equal
  return a.Name == b.Name;
}

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.