viswa teja
viswa teja

Reputation: 29

Compare two arrays having objects and remove duplicates from first array

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"}
]

Upvotes: 0

Views: 185

Answers (3)

call-me
call-me

Reputation: 726

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

Upvotes: 0

A l w a y s S u n n y
A l w a y s S u n n y

Reputation: 38552

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

Upvotes: 1

Harmandeep Singh Kalsi
Harmandeep Singh Kalsi

Reputation: 3345

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

Upvotes: 0

Related Questions