How to compare 2 arrays, check for duplicates, and keep one?

Hey guys,

I’m trying to compare 2 arrays, check for duplicates, and keep only one. After googling the below can remove duplicates but I do want to keep at least 1 and get rid of the rest so that my new array has all the necessary items but only once. No repeats. Any suggestions??

`
// Returns array that duplicates completely removed

let removeDuplicates = categoryArray.filter(value => !userArray.includes(value))
`

Thanks!

It looks like the logic here isn’t working correctly. The filter method will send values to new array where the function returns TRUE. So with the logic written it only returns True if value from categoryArray is not included in userArray. So it is only sending items not duplicated.
Does it have to be a filter method?

So if the two arrays were:

[1, 2, 3, 4]

and

[2, 3, 5]

You want the final array to be:

[1, 2, 3, 4, 5]

Correct?

If so, one of the easiest ways would be to concatenate the two arrays together, then create a Set of the new array, and then convert the Set back into an array. This can be done with a single line of code.

2 Likes

Thank you for the reply and this worked. I have never used Set before so this was a great thing to learn.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.