Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 230
Tauren Avatar asked Jun 03 '10 04:06

Tauren


People also ask

How do you get the elements of one array which are not present in another array using JavaScript?

Use the . filter() method on the first array and check if the elements of first array are not present in the second array, Include those elements in the output.

How do you check if an array contains any element of another array JavaScript?

Use the inbuilt ES6 function some() to iterate through each and every element of first array and to test the array. Use the inbuilt function includes() with second array to check if element exist in the first array or not. If element exist then return true else return false.

How do you check if an array contains all the elements of another array?

You can try with Array. prototype. every() : The every() method tests whether all elements in the array pass the test implemented by the provided function.


1 Answers

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) )

like image 198
kofifus Avatar answered Sep 18 '22 17:09

kofifus