1

I am stuck on this problem. I have two arrays (simplified here)

const array1 = [1,2,3]
const array2 = [1,2]

I want to create a new array comparing the similar values between them and removing them so the final array would be

const finalArray = [3]

I have tried this among many other combinations of mapping filtering, for loops, I don't remember what else I've tested hence only have this too post

var finalArray = array1.filter(function (e) {
      return array2.indexOf(e) > -1;
    });

The result of this is just

[1,2]

Hoping someone can point out a solution, I'm sure it's obvious, but I am scratching my head at this point
Anders Kitson
  • 1,413
  • 6
  • 38
  • 98
  • 1
    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) – MisteriosM Mar 26 '21 at 23:45

3 Answers3

1

you just messed up the meaning of the test, and your code should be:

array1.filter(function (e) { return array2.indexOf(e) === -1 })

but for this kind of case it is better to use the array.includes method
(and in the case of an array made of objects use the array.some method)

const array1 = [1,2,3]
const array2 = [1,2]

const finalArray = array1.filter(x=>!array2.includes(x))

console.log( finalArray )
Mister Jojo
  • 20,093
  • 6
  • 21
  • 40
1

This is a douplicate question to How to get the difference between two arrays in JavaScript?

Check out Luis Sieira's Answer for all possible set theory solutions

MisteriosM
  • 85
  • 9
-1

You could also use a Set to remove duplicate values.

Spread both of your arrays into a combined array to form a set. Then spread your Set back into an array to have an array with only unique values.

const array1 = [1,2,3]
const array2 = [1,2]

const deduped = [...new Set([...array1, ...array2])]
user5513663
  • 11
  • 1
  • 2