I'm getting stacked in an issue in JavaScript.
I have two arrays and I want to check if they intersect on some elements then delete those elements and return new array without the intersected elements.
example :
Array A (
[0] => 0 [1] => 1
)
Array B (
[0] => 2 [1] => 1
)
I want to check them and return:
Array result (
[0] => 0 [1] => 2
)
How can i do this in JavaScript?
Checkout the library underscore.js.
Say you have two arrays,
var a = [1, 2];
var b = [2, 3];
First find the union.
var all = _.union(a, b);
Then find the intersection.
var common = _.intersection(a, b);
The final answer should be the difference between the union, and the intersection.
var answer = _.difference(all, common)
Using Array.filter, Array.lastIndexOf, and Array.indexOf:
var array1 = [1,2,3,4,5];
var array2 = [2,3];
var unique = array1.concat(array2)
.filter(function (item, index, array) {
return array.indexOf(item) == array.lastIndexOf(item);
})
Neither method is 100% cross browser by default, but both links having safe shims for IE <= 8
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