0

Array 1

[ { "id": 1, "name": "Test" }, { "id": 2, "name": "Test2" } ]

Array 2

[ { "id": 1, "name": "Test3" }, { "id": 2, "name": "Test4" }, { "id": 3, "name": "Test2" } ]

If item exists in Array 2, I need to remove it from Array 1, so Test2 would be removed from Array 1. How can I loop through both arrays and check the name value's presence in Array 2 in order to remove it from Array 1?

10
  • Do you have a specific question about this? Why is the element with ID 1 not removed? Commented Aug 28, 2015 at 23:29
  • So, you are comparing by name, not id? Commented Aug 28, 2015 at 23:30
  • You should be able to use array_filter for this. Commented Aug 28, 2015 at 23:31
  • Convert Array 2 to an object that uses the IDs as property names. Then loop through Array 1, removing the elements that can't be found in the object. Commented Aug 28, 2015 at 23:31
  • 1
    @RocketHazmat That's PHP. You mean Array.prototype.filter. Commented Aug 28, 2015 at 23:32

3 Answers 3

1

I'm a big fan of underscorejs for this kind of thing...

array1 = _.reject(array1, function(e1) {
    return _.find(array2, function(e2) { return e1.name == e2.name });
});
Sign up to request clarification or add additional context in comments.

Comments

0

Try this:

var existingIds = array2.map(function (item) { // create a list of existing ids in array 2
        return item.id;
    });

var filteredArray = array1.filter(function (item) { // check each item against existingIds, and if not found there return it
        return existingIds.indexOf(item.id) === -1;
    });

Comments

0

To do this without doing an O(n^2) search, we can do it looping once on each array, with a little extra memory overhead.

var map = new Map();
array2.forEach(function(item) {
    map.set(item.name, true);
});
var result = array1.filter(function(item) {
    return !map.has(item.name);
});

Note: I used Map simply because it has additional features, such as setting keys based on any value. A simple object can be used.

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.