Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Merging and rectifying arrays in JavaScript
We need to create a JavaScript function that merges two arrays and removes duplicates, ensuring each element appears only once in the final result.
Problem
We are required to write a JavaScript function that takes in two arrays of numbers, arr1 and arr2, as the first and the second arguments.
Our function should merge the elements of both these arrays into a new array and if upon merging or before merging there exists any duplicates, we should delete the excess duplicates so that only one copy of each element is present in the merged array.
The order here is not so important but the frequency of elements (which should be 1 for each element) is important.
For example, if the input to the function is:
const arr1 = [6, 5, 2, 1, 8]; const arr2 = [3, 4, 6, 8, 9];
Then the output should be:
[6, 5, 2, 1, 8, 3, 4, 9]
Method 1: Using Set (Recommended)
The most efficient approach is to use JavaScript's Set data structure, which automatically handles duplicates:
const arr1 = [6, 5, 2, 1, 8];
const arr2 = [3, 4, 6, 8, 9];
const mergeAndRectify = (arr1 = [], arr2 = []) => {
return [...new Set([...arr1, ...arr2])];
};
console.log(mergeAndRectify(arr1, arr2));
[ 6, 5, 2, 1, 8, 3, 4, 9 ]
Method 2: Using includes() Method
Here's the original approach using the includes() method to check for duplicates:
const arr1 = [6, 5, 2, 1, 8];
const arr2 = [3, 4, 6, 8, 9];
const mergeAndRectify = (arr1 = [], arr2 = []) => {
const result = [...arr1];
for (let element of arr2) {
if (!result.includes(element)) {
result.push(element);
}
}
return result;
};
console.log(mergeAndRectify(arr1, arr2));
[ 6, 5, 2, 1, 8, 3, 4, 9 ]
Method 3: Using Filter and indexOf
Another approach using filter() to remove duplicates after concatenation:
const arr1 = [6, 5, 2, 1, 8];
const arr2 = [3, 4, 6, 8, 9];
const mergeAndRectify = (arr1 = [], arr2 = []) => {
const combined = [...arr1, ...arr2];
return combined.filter((item, index) => combined.indexOf(item) === index);
};
console.log(mergeAndRectify(arr1, arr2));
[ 6, 5, 2, 1, 8, 3, 4, 9 ]
Performance Comparison
| Method | Time Complexity | Space Complexity | Best For |
|---|---|---|---|
| Set | O(n + m) | O(n + m) | Large arrays, best performance |
| includes() | O(n × m) | O(n + m) | Small arrays, readable code |
| filter + indexOf | O((n + m)²) | O(n + m) | When order preservation is critical |
Conclusion
The Set approach is the most efficient for merging arrays and removing duplicates. Use includes() for smaller datasets when code readability is preferred over performance.
