JavaScript Program to Merge Two Arrays and Remove Duplicate Items
Working with arrays is a common task for many JavaScript developers. Often, we need to merge two arrays and remove any duplicate items to create a new array that contains all the unique elements from both arrays.
Fortunately, JavaScript provides several built-in methods that make this task easy and efficient. In this article, we'll explore how to merge two arrays using the concat() method and remove any duplicate items using the Set object.
We also have an interactive JavaScript course where you can learn JavaScript from basics to advanced and get certified. Check out the course and learn more from here.
Program to Merge Two Arrays and Remove Duplicate Items Using concat() and for Loop
In the program given below, the two array elements are merged together and the duplicate elements are removed.
- The two arrays are merged using the
concat()
method.
- The
for...of
loop is used to loop through all the elements of arr.
- The
indexOf()
method returns -1 if the element is not in the array.
Hence, during each iteration, if the element equals -1, the element is added to the uniqueArr array using the push()
method.
?// JavaScript Program to merge and remove duplicate values from an array
function getUniqueAfterMerge(arr1, arr2){
// merge two arrays
let arr = arr1.concat(arr2);
let uniqueArr = [];
// looping through array
for(let i of arr) {
if(uniqueArr.indexOf(i) === -1)
uniqueArr.push(i);
}
console.log(uniqueArr);
}
const arr1 = [1, 2, 3 , 4 , 5];
const arr2 = [2, 3, 5]
getUniqueAfterMerge(arr1, arr2);
[1, 2, 3, 4, 5]
Program to Merge Two Arrays and Remove Duplicate Items Using Spread Syntax and Set
In the program given below, two arrays are merged together and Set
is used to remove duplicate items from an array.
Sets are a type of associative container in which each element has to be unique because the value of the element identifies it. The values are stored in a specific sorted order i.e. either ascending or descending.
- Two array elements are merged together using the spread syntax [
... ]
- The array is converted to
Set
and all the duplicate elements are automatically removed.
- The spread syntax
...
is then used to include all the elements of the set back to an array.
// JavaScript Program to merge and remove duplicate value from an array
function getUniqueAfterMerge(arr1, arr2){
// merge two arrays
let arr = [...arr1, ...arr2];
// removing duplicate
let uniqueArr = [...new Set(arr)];
console.log(uniqueArr);
}
const arr1 = [1, 2, 3 , 4 , 5];
const arr2 = [2, 3, 5]
// calling the function
getUniqueAfterMerge(arr1, arr2);
[1, 2, 3, 4, 5]
Conclusion
Using built-in JavaScript methods such as concat() and Set, it is simple to merge two arrays and remove duplicate elements. By utilising these methods, we can manipulate arrays effectively and develop more effective and efficient programmes.