I have two arrays
var a = [4,8,9,7];
var b = [1,5,7,3,9];
I want result
[4,8,1,5,3]
I have tried using filter-
function diffArray(arr1, arr2) {
var newArr = [];
var newArr2 = [];
newArr = arr1.filter(function(e) {
return arr2.indexOf(e) < 0;
});
newArr2 = arr2.filter(function(e) {
return arr1.indexOf(e) < 0;
});
var arr = newArr.concat(newArr2);
return arr;
}
Is there any better way to get the same result.
You could check the index and last index of the item and filter only if the index is the same.
var a = [4, 8, 9, 7],
b = [1, 5, 7, 3, 9],
unique = a.concat(b).filter((v, _, a) => a.indexOf(v) === a.lastIndexOf(v));
console.log(unique);
I can do like this.
var a = [4, 8, 9, 7];
var b = [1, 5, 7, 3, 9];
var c = b.reduce((r, o) => {
if (r.indexOf(o) !== -1) {
r.splice(r.indexOf(o), 1);
} else {
r.push(o);
}
return r;
}, a);
console.log(c);
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