Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
143
rated 0 times [  149] [ 6]  / answers: 1 / hits: 91064  / 14 Years ago, thu, june 3, 2010, 12:00:00

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?


More From » jquery

 Answers
29
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/


[#96598] Tuesday, June 1, 2010, 14 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
morganm

Total Points: 626
Total Questions: 95
Total Answers: 95

Location: South Sudan
Member since Sun, Jul 11, 2021
3 Years ago
;