I have two arrays in JavaScript, and I want to create a new array that contains only the unique values from both arrays. How can I do this in JavaScript?
const arr1 = ['apple', 'banana', 'cherry', 'date', 'elderberry'];
const arr2 = ['cherry', 'date', 'elderberry', 'fig', 'grape'];
I’ve tried using the concat
method to combine the arrays and then using a Set
to remove duplicates, but that doesn’t work because the Set
considers arrays to be different objects even if they have the same values.
I’ve also tried using a for
loop to iterate through both arrays and an if
statement to determine whether each word already exists in the new array, but that seems wasteful and doesn’t function if the arrays include a large number of duplicate words.
Can someone please point me in the direction of a more reliable and efficient JavaScript method for generating an array of distinct words from two arrays? I’m grateful.
2
Answers
To get a set of unique strings, first concat the arrays into a single array using the spread (
...
) operator, and use the new array as the parameter toSet
:To convert the
Set
to an array:Could you please give it try?