-3
var firstOne = [
    { id: 22, value: 'hi there' },
    { id: 28, value: 'here' },
    { id: 77, value: 'what' }
];

var secondOne = [
    { id: 2, value: 'bond' },
    { id: 8, value: 'foobar' },
    { id: 87, value: 'what' }
];

I'm looking for the best approach to compare two arrays of objects by value. If value is same in both, then remove it from firstOne which would result in:

var firstOne = [
    { id: 22, value: 'hi there' },
    { id: 28, value: 'here' }
];

var secondOne = [
    { id: 2, value: 'bond' },
    { id: 8, value: 'foobar' },
    { id: 87, value: 'what' }
];

Javascript or Angular solutions would be appreciated. Thanks

relyt
  • 679
  • 6
  • 14
  • 26
  • 3
    We aren't a code writing service. Please write your own code and present a problem and we'll be glad to assist you – Andrew Li Aug 31 '16 at 04:26
  • "Javascript or Angular solutions" is kind of like "pick up by car or Toyota Corolla". Angular is a framework *in JavaScript*. – Amadan Aug 31 '16 at 04:29
  • 1
    Possible duplicate of [Compare two arrays of objects and remove items in the second one that have the same property value](http://stackoverflow.com/questions/17830390/compare-two-arrays-of-objects-and-remove-items-in-the-second-one-that-have-the-s) – yash Aug 31 '16 at 04:37
  • @AndrewL. Roger that. I'll give it one more shot – relyt Aug 31 '16 at 12:30

1 Answers1

1

You could use Set for the filtering.

var firstOne = [{ id: 22, value: 'hi there' }, { id: 28, value: 'here' }, { id: 77, value: 'what' }],
    secondOne = [{ id: 2, value: 'bond' }, { id: 8, value: 'foobar' }, { id: 87, value: 'what' }],
    mySet = new Set;

secondOne.forEach(function (a) {
    mySet.add(a.value);
});

firstOne = firstOne.filter(function (a) {
    return !mySet.has(a.value);
});

console.log(firstOne);

ES6

var firstOne = [{ id: 22, value: 'hi there' }, { id: 28, value: 'here' }, { id: 77, value: 'what' }],
    secondOne = [{ id: 2, value: 'bond' }, { id: 8, value: 'foobar' }, { id: 87, value: 'what' }],
    mySet = new Set;

secondOne.forEach(a => mySet.add(a.value));
firstOne = firstOne.filter(a => !mySet.has(a.value));

console.log(firstOne);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392