Reputation: 3945
I would like to compare two arrays in jquery and return a new array of all the elements that do not match. so if I build a function like so:
function (parent, child) {}
I should compare child
to parent
and return a new array of all the elements in child that do not match parent. an example would be
parent = ['apple', 'banana'];
child = ['fruit'];
compare child to parent and get back and array: ['fruit']
as fruit
is not in parent. I looked for methods to do this and saw this solution but I am not sure if this is what I want or not.
Upvotes: 0
Views: 198
Reputation: 2533
Be careful, using the keyword 'parent' may have unexpected side effects. In the version of Chrome I'm using, it seems to refer to Window.
Vanilla JavaScript solution, quick and easy:
var findDifference = function (elder, sibling) {
var difference = [];
for(var i = 0; i < sibling.length; i++){
if(elder.indexOf(sibling[i]) < 0){
difference.push(sibling[i]);
}
}
return difference;
};
var elder = ['apple', 'banana'];
var sibling = ['fruit'];
findDifference(elder, sibling); // => ['fruit']
Upvotes: 1
Reputation: 339
You might want to look at Underscore.js (http://underscorejs.org/#difference), which has a function just for that. It returns the values from array that are not present in the other arrays.
_.difference([1, 2, 3, 4, 5], [5, 2, 10]);
=> [1, 3, 4]
To justify the use of yet another library: you might find tons of other useful utilities there ;)
Upvotes: 2