3

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.

Sanjita
  • 103
  • 5
  • Possible duplicate of [How to merge two arrays in JavaScript and de-duplicate items](https://stackoverflow.com/questions/1584370/how-to-merge-two-arrays-in-javascript-and-de-duplicate-items) – Bùi Đức Khánh Nov 25 '17 at 10:57
  • So you want the symmetric difference? Loop over both arrays, assign the array values as keys to an object with the value `1`, if the key already exists, set the value to `0`, then take only the keys that have value `1` (with `Object.entries` and `filter`). – Sebastian Simon Nov 25 '17 at 10:57
  • 1
    Possible duplicate of [symmetric difference between arrays](https://stackoverflow.com/questions/38498681/symmetric-difference-between-arrays) – Sebastian Simon Nov 25 '17 at 10:58
  • @KhánhBùiĐức No, this is not about the symmetric difference required here. – Sebastian Simon Nov 25 '17 at 10:59
  • Once I saw this question in Codewars.com – qxg Nov 25 '17 at 11:01

2 Answers2

3

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);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
1

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);
Mritunjay Upadhyay
  • 1,004
  • 1
  • 15
  • 27