1

I have 2 arrays and a method that finds differences.
But at the moment, the method shows the result of the difference between both arrays.
How to implement comparisons of the first array with the second so that only the differences of the first array are returned.

let test1 = ['1', '2', '3', '4/2', '5/4', '6-2'];
let test2 = ['1', '2', '3', '5/4', '4/2', '6-1', '7/2', '8-2'];


const diff = function (arr1, arr2) {
    return arr1.filter(i => !arr2.includes(i)).concat(arr2.filter(i => !arr1.includes(i)))
}

console.log(diff(test1, test2));

Expected to return a value: 6-2

Mister Jojo
  • 20,093
  • 6
  • 21
  • 40
Alice
  • 158
  • 8
  • Also relevant: [this answer that defines set operations](https://stackoverflow.com/a/58626840/) – VLAZ Oct 28 '20 at 16:27

2 Answers2

2

Put all the numbers of 2nd array in a Set and then use .filter() method on the first array to filter those elements of 1st array that are not present in the Set.

let test1 = ['1', '2', '3', '4/2', '5/4', '6-2'];
let test2 = ['1', '2', '3', '5/4', '4/2', '6-1', '7/2', '8-2'];


const diff = function(arr1, arr2) {
  const set = new Set(arr2);
  return arr1.filter(n => !set.has(n));
}

console.log(diff(test1, test2));

Note: You could also use !arr2.includes(n) condition in the filter() method but then for each number in arr1, we will go through each element in arr2 which is not ideal. Using a Set, we don't have to check each element in arr2.

Yousaf
  • 27,861
  • 6
  • 44
  • 69
1

You need to filter on the first array all elements which are not in the second array so :

const test1 = ['1', '2', '3', '4/2', '5/4', '6-2'];
const test2 = ['1', '2', '3', '5/4', '4/2', '6-1', '7/2', '8-2'];

const differences = test1.filter(o => !test2.includes(o));

console.log(differences);
Nulji
  • 447
  • 3
  • 9