Write a JavaScript Program to Merge Two Arrays and Remove Duplicate Items

Merging two arrays is a common task in JavaScript programming.

In some cases, you might want to remove any duplicates that occur in the resulting array.

In this tutorial, we’ll explore how to merge two arrays and remove any duplicate items.

Merging Two Arrays

To merge two arrays in JavaScript, we can use the concat method.

This method combines two or more arrays and returns a new array. Here’s an example:

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

In the example above, we defined two arrays, arr1 and arr2. We then used the concat method to combine them into a new array called mergedArray.

Removing Duplicate Items

To remove duplicate items from an array, we can use the Set object.

The Set object lets you store unique values of any type, including primitive values or object references. Here’s an example:

const arr = [1, 2, 3, 3, 4, 5, 5];
const uniqueArray = Array.from(new Set(arr));
console.log(uniqueArray); // [1, 2, 3, 4, 5]

In the example above, we defined an array arr with some duplicate items.

We then created a new Set object using the Set constructor and passed arr as an argument.

We then converted the Set object back to an array using the Array.from method and stored the result in uniqueArray.

The resulting array contains only the unique items from the original array.

Merging Two Arrays and Removing Duplicate Items

To merge two arrays and remove any duplicate items, we can use the concat method to merge the arrays and then use the Set object to remove duplicates. Here’s an example:

const arr1 = [1, 2, 3];
const arr2 = [2, 3, 4];
const mergedArray = arr1.concat(arr2);
const uniqueArray = Array.from(new Set(mergedArray));
console.log(uniqueArray); // [1, 2, 3, 4]

In the example above, we defined two arrays, arr1 and arr2. We then used the concat method to merge them into a new array called mergedArray.

We then used the Set object to remove duplicates and stored the result in uniqueArray. The resulting array contains only the unique items from the two original arrays.


Conclusion

Merging two arrays and removing duplicate items is a common task in JavaScript programming.

We can use the concat method to merge two arrays and the Set object to remove duplicates.

By combining these two techniques, we can easily create an array that contains only the unique items from two arrays.