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?
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.
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.
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.
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)
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With