-1

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.

Vishal
  • 1
  • 1
  • 2
    Please show what you tried with `Set`; I'm sure it can be used to achieve your goal. – mykaf Apr 27 '23 at 16:50
  • 1
    Welcome to [so] - Please take the [tour] and check out the [ask] page for tips on how to improve this question. For starters, please include a [mre] of your efforts for faster troubleshooting – blurfus Apr 27 '23 at 16:52
  • What's your expected output? Should it be the values that only appear in one of the arrays or all the values from both arrays, but only listed once? – mykaf Apr 27 '23 at 16:59

2 Answers2

1

Could you please give it try?

const arr1 = ['apple', 'banana', 'cherry', 'date', 'elderberry'];
const arr2 = ['cherry', 'date', 'elderberry', 'fig', 'grape'];

const mergedArr = [...new Set([...arr1, ...arr2])];

console.log(mergedArr); // Output: ['apple', 'banana', 'cherry', 'date', 'elderberry', 'fig', 'grape']
mistertandon
  • 1,424
  • 14
  • 15
  • but 'date' is not unique, it should not be in the output (OR maybe I misunderstood the requirements) – blurfus Apr 27 '23 at 16:55
0

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 to Set:

const uniques = new Set([...arr1, ...arr2])

To convert the Set to an array:

[...uniques]
Sal Rahman
  • 4,607
  • 2
  • 30
  • 43