Search code examples
javascriptjqueryalgorithmarrays

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?


Solution

  • 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/