-1

I have to do an exercise where in a function that receives two arrays, it compares them and returns the difference between them, both the difference of array1 and the difference of array2.

I have reviewed similar questions but no solution works because they only compare one array and I need the differentiation of the two arrays

i have this arrays

const arr1 = ["andesite", "grass", "dirt", "pink wool", "dead shrub"];
const arr2 = ["diorite", "andesite", "grass", "dirt", "dead shrub"];

and i hope this result

["diorite", "pink wool"]

if not exist difference, return this

[]
  • 2
    Does this answer your question? [How to get the difference between two arrays in JavaScript?](https://stackoverflow.com/questions/1187518/how-to-get-the-difference-between-two-arrays-in-javascript) – Charlie Bamford Apr 27 '21 at 17:07

2 Answers2

0

This sounds like a perfect place to use the array every() method. Essentially, we can build a function that takes in any number of arrays, flattens them into a single array, iterates over that new array and filters to only items that do not appear in every array:

const arr1 = ["andesite", "grass", "dirt", "pink wool", "dead shrub"];
const arr2 = ["diorite", "andesite", "grass", "dirt", "dead shrub"];

const getDifferences = (...arrays) => arrays.flat().filter(e => !arrays.every(array => array.includes(e)));

const differences = getDifferences(arr1, arr2);

console.log(differences);

If you would prefer to filter to items that only appear in exactly one array, you can do so like this:

const arr1 = ["dirt", "pink wool", "dead shrub"];
const arr2 = ["diorite", "andesite", "grass"];
const arr3 = ["andesite", "grass", "dirt", "dead shrub"];

const getDifferences = (...arrays) => arrays.flat().filter(e => arrays.filter(array => array.includes(e)).length === 1);

const differences = getDifferences(arr1, arr2, arr3);

console.log(differences);
Brandon McConnell
  • 5,776
  • 1
  • 20
  • 36
0

You can simply put all the unique elements from each array into a new array and then reduce it into a new array that only contains the elements if it's found in 1 of 2 original arrays. For example:

const arr1 = ["andesite", "grass", "dirt", "pink wool", "dead shrub"];
const arr2 = ["diorite", "andesite", "grass", "dirt", "dead shrub"];

const difference = [...new Set(arr1), ...new Set(arr2)].reduce((accum, el) => {
  if (arr1.includes(el) && !arr2.includes(el)) {
    accum.push(el);
  } else if (!arr1.includes(el) && arr2.includes(el)) {
    accum.push(el);
  }
  return accum;
}, []);

console.log(difference);
Tom O.
  • 5,730
  • 2
  • 21
  • 35