Reputation: 861
How do I compare two arrays in jquery and then remove the items from the first array that do not match in both arrays?
I start with this
var listOne = [1,2,3,4,6,7];
var listTwo = [2,5,6];
I want the result to be like this only listOne is changed.
var listOne = [2,6];
var listTwo = [2,5,6];
Upvotes: 2
Views: 2557
Reputation: 3412
I would suggest to use .grep and .inArray in jQuery,Like that:
var array1 = [1, 2, 3, 4, 6, 7];
var array2 = [2, 5, 6];
var foo = [];
var foo2 = [];
var result = [];
var i = 0;
jQuery.grep(array2, function(el) {
if (jQuery.inArray(el, array1) == -1) {
foo.push(el);
} else {
foo2.push(el);
}
i++;
});
alert(foo2);
alert(foo);
result = $.merge(foo2, foo)
alert(result);
http://jsfiddle.net/csdtesting/u9xES/644/
Upvotes: 2
Reputation: 707496
For medium sized arrays, the brute force solution should work fine. What you describe seems like it basically just comes down to removing elements from one array that are not present in the other array. So, traverse the first array and remove any element that is not found in the second array:
function removeElems(src, permitted) {
// traverse array backwards so iteration not affected when we remove current item
for (var i = src.length - 1; i >= 0; i--) {
// if src element not found in permitted array, remove it from src
if (permitted.indexOf(src[i]) === -1) {
src.splice(i, 1);
}
}
}
var listOne = [1,2,3,4,6,7];
var listTwo = [2,5,6];
removeElems(listOne, listTwo);
Working demo: http://jsfiddle.net/jfriend00/1n1fbpgm/
If listTwo
could be very long, I'd probably put all the elements of that array into a temporary object first so checking if an item was in the array was just an object key lookup rather than a linear array search, but for small/medium sized arrays or situations where performance isn't super criticial that extra complexity is likely not warranted.
Upvotes: 2
Reputation: 6632
jQuery is just the wrong library to do so. There's a nice library called lodash
that has a function difference
that does what you're asking about.
Upvotes: 0