-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.

3
  • 2
    Please show what you tried with Set; I'm sure it can be used to achieve your goal. Commented Apr 27, 2023 at 16:50
  • 1
    Welcome to Stack Overflow - Please take the tour and check out the How to Ask page for tips on how to improve this question. For starters, please include a minimal reproducible example of your efforts for faster troubleshooting Commented Apr 27, 2023 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? Commented Apr 27, 2023 at 16:59

2 Answers 2

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']
Sign up to request clarification or add additional context in comments.

1 Comment

but 'date' is not unique, it should not be in the output (OR maybe I misunderstood the requirements)
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]

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.