0

I want to find unique elements in a which do not exist in b on the basis of name property


EXPECTED OUTPUT
var data= [{"name":"rashffffish","color":"blue" }];

var a =[{"name":"sam","color":"red" }, {"name":"rash","color":"blue" },{"name":"rashffffish","color":"blue" }];


var b = [{"name":"sam","color":"red" },{"name":"rash","color":"red" }];


var data = [];
b.map((n)=>{
  for(i=0;i<a.length;i++) {
    if(n.name!= a[i].name){
      data.push(a[i]);
    }
  }
})

console.log(data);
Suren Srapyan
  • 66,568
  • 14
  • 114
  • 112
art
  • 226
  • 3
  • 11
  • 30

2 Answers2

1

Use Array#filter to filter the a array and pass a predicate which uses Array#some to try to find an item. When there is no match, get those items

const a =[
   {"name":"sam","color":"red" }, 
   {"name":"rash","color":"blue" },
   {"name":"rashffffish","color":"blue" }
];

const b = [
   {"name":"sam","color":"red" },
   {"name":"rash","color":"red" }
];

const filtered = a.filter(itemA => !b.some(itemB => itemA.name === itemB.name));

console.log(filtered);
Suren Srapyan
  • 66,568
  • 14
  • 114
  • 112
  • Please look for duplicates for questions like these. Since you know the solution, you are more likely to find a better dupe. – Rajesh Nov 17 '17 at 05:55
0

From your code...

var a = [{
  "name": "sam",
  "color": "red"
}, {
  "name": "rash",
  "color": "blue"
}, {
  "name": "rashffffish",
  "color": "blue"
}];


var b = [{
  "name": "sam",
  "color": "red"
}, {
  "name": "rash",
  "color": "red"
}];


var data = a;
b.forEach((n) => {
  for (i = 0; i < data.length; i++) {
    if (n.name === a[i].name) {
      var ind= data.indexOf(a[i]);
      data.splice(ind, 1);
    }
  }
})
console.log(data);
Sankar
  • 6,908
  • 2
  • 30
  • 53
  • Please look for duplicates for questions like these. Since you know the solution, you are more likely to find a better dupe. – Rajesh Nov 17 '17 at 05:55
  • @Rajesh Hope, we already talked about [this](https://stackoverflow.com/questions/45627515/clone-input-value-to-another-input-value/45627538#comment78214497_45627538). I know what I'm doing. – Sankar Nov 17 '17 at 06:04
  • If you remember our conversation, It was pretty clear that its a bad practice to answer to answer a dupe. Your answer may not be wrong, but its a duplication of content which is wrong. So I'd stick to my opinion. – Rajesh Nov 17 '17 at 07:21
  • Also I just realized, you are using `b.map` but you are not accepting its value or returning anything from it. So **why map**? Why not `.forEach`? – Rajesh Nov 17 '17 at 07:23
  • @Rajesh I agree with your last comment and updated the answer. You stick to whatever you got in your mind that I don't care. – Sankar Nov 17 '17 at 07:33