Javascript algorithm to find elements in array that are not in another array

Posted by Tauren on Stack Overflow See other posts from Stack Overflow or by Tauren
Published on 2010-06-03T04:14:44Z Indexed on 2010/06/03 4:24 UTC
Read the original article Hit count: 280

Filed under:
|
|
|

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?

© Stack Overflow or respective owner

Related posts about JavaScript

Related posts about jQuery