Javascript algorithm to find elements in array that are not in another array
I'm looking for a good algorithm to get all the elements in one array that are not elements in another array. So given these arrays:
var x = ["a","b","c","t"];
var y = ["d","a","t","e","g"];
I want to end up with this array:
var z = ["d","e","g"];
I'm using jquery, so I can take advantage of $.each()
and $.inArray()
. Here's the solution I've come up with, but it seems like there should be a better way.
// goal is to get rid of values in y if they exist in x
var x = ["a","b","c","t"];
var y = ["d","a","t","e","g"];
var z = [];
$.each(y, function(idx, value){
if ($.inArray(value,x) == -1) {
z.push(value);
}
});
alert(z); // should be ["d","e","g"]
Here is the code in action. Any ideas?
in ES6 simply
const a1 = ["a", "b", "c", "t"];
const a2 = ["d", "a", "t", "e", "g"];
console.log( a2.filter(x => !a1.includes(x)) );
(another option is a2.filter(x => a1.indexOf(x)===-1)
)
Late answer with the new ECMA5 javascript:
var x = ["a","b","c","t"];
var y = ["d","a","t","e","g"];
myArray = y.filter( function( el ) {
return x.indexOf( el ) < 0;
});
var z = $.grep(y, function(el){return $.inArray(el, x) == -1});
Also, that method name is too short for its own good. I would expect it to mean isElementInArray, not indexOf.
For a demo with objects, see http://jsfiddle.net/xBDz3/6/
Here's an alternative using underscore.js:
function inAButNotInB(A, B) {
return _.filter(A, function (a) {
return !_.contains(B, a);
});
}
I am quite late now but maybe it will be helpful for someone.
If the array is not just a simple array but an array of objects then the following can be used:
var arr1 = [
{
"prop1": "value1",
"prop2": "value2",
},
{
"prop1": "value3",
"prop2": "value4",
},
{
"prop1": "value5",
"prop2": "value6",
},
];
var arr2 = ['value1','value3', 'newValue'];
// finds all the elements of arr2 that are not in arr1
arr2.filter(
val => !arr1.find( arr1Obj => arr1Obj.prop1 === val)
); // outputs "newValue"