Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get unique item from two different array in javascript

Tags:

javascript

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.

like image 909
Sanjita Avatar asked Jun 13 '26 14:06

Sanjita


2 Answers

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);
like image 177
Nina Scholz Avatar answered Jun 16 '26 04:06

Nina Scholz


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);
like image 29
Mritunjay Upadhyay Avatar answered Jun 16 '26 02:06

Mritunjay Upadhyay