ArticleZip > How To Merge Two Arrays In Javascript And De Duplicate Items

How To Merge Two Arrays In Javascript And De Duplicate Items

Arrays are fundamental in JavaScript programming, and knowing how to merge and de-duplicate arrays can be a handy skill to have in your coding toolbox. In this article, we will explore a straightforward way to combine two arrays in JavaScript while removing any duplicate elements.

Let's get started by understanding the steps to merge two arrays and eliminating duplicates effectively.

**Step 1: Define Your Arrays**
To begin, let's create two arrays that we want to merge and de-duplicate. For example, let's consider the following arrays:

Javascript

const arr1 = [1, 2, 3, 4];
const arr2 = [3, 4, 5, 6];

**Step 2: Merge Arrays Using the Spread Operator**
One of the simplest methods to merge arrays in JavaScript is by using the spread operator (`...`). By using this operator, we can easily copy the elements from both arrays into a new array without altering the original arrays.

Here's how you can merge `arr1` and `arr2` into a new array:

Javascript

const mergedArray = [...arr1, ...arr2];
console.log(mergedArray); // Output: [1, 2, 3, 4, 3, 4, 5, 6]

**Step 3: Remove Duplicates**
Now that we have a merged array, our next goal is to remove any duplicate elements from it. To achieve this, we can leverage the `Set` object in JavaScript. Since a `Set` only allows unique values, we can easily remove duplicates by converting our array into a `Set` and then back to an array.

Here's how we can de-duplicate the merged array:

Javascript

const uniqueArray = [...new Set(mergedArray)];
console.log(uniqueArray); // Output: [1, 2, 3, 4, 5, 6]

By converting our merged array into a `Set` and then back to an array, we filtered out any duplicate elements, leaving us with a clean array containing unique values.

**Step 4: Putting It All Together**
Let's combine all the steps into a simple function that can merge two arrays and remove duplicates:

Javascript

function mergeAndDeDuplicateArrays(arr1, arr2) {
  const mergedArray = [...arr1, ...arr2];
  const uniqueArray = [...new Set(mergedArray)];
  return uniqueArray;
}

// Usage
const arr1 = [1, 2, 3, 4];
const arr2 = [3, 4, 5, 6];

const result = mergeAndDeDuplicateArrays(arr1, arr2);
console.log(result); // Output: [1, 2, 3, 4, 5, 6]

In conclusion, merging two arrays in JavaScript and de-duplicating the elements is a handy technique that can be achieved with simple and efficient code. By following the steps outlined in this article, you can seamlessly combine arrays while ensuring uniqueness in the final array.