skip to Main Content

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


  1. 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]
    
    Login or Signup to reply.
  2. 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']
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search