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.

5
  • Possible duplicate of How to merge two arrays in JavaScript and de-duplicate items Commented Nov 25, 2017 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). Commented Nov 25, 2017 at 10:57
  • 1
    Possible duplicate of symmetric difference between arrays Commented Nov 25, 2017 at 10:58
  • @KhánhBùiĐức No, this is not about the symmetric difference required here. Commented Nov 25, 2017 at 10:59
  • Once I saw this question in Codewars.com Commented Nov 25, 2017 at 11:01

2 Answers 2

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);

Sign up to request clarification or add additional context in comments.

Comments

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);

2 Comments

But why is this better?
No Sir, Nina Scholz's answer is best. You can check it out

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.