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
Selected Reading
Merge and remove duplicates in JavaScript Array
Merging arrays and removing duplicates is a common task in JavaScript. There are several approaches to accomplish this, from traditional loops to modern ES6 methods.
Problem Statement
Given two arrays of numbers, we need to combine them into a single array where each element appears only once.
const arr1 = [2, 4, 5, 3, 7, 8, 9];
const arr2 = [1, 4, 5, 2, 3, 7, 6];
console.log("Array 1:", arr1);
console.log("Array 2:", arr2);
Array 1: [ 2, 4, 5, 3, 7, 8, 9 ] Array 2: [ 1, 4, 5, 2, 3, 7, 6 ]
Using Set and Spread Operator (Recommended)
The most efficient modern approach uses Set to automatically remove duplicates:
const arr1 = [2, 4, 5, 3, 7, 8, 9];
const arr2 = [1, 4, 5, 2, 3, 7, 6];
const mergeUnique = (first, second) => {
return [...new Set([...first, ...second])];
};
console.log(mergeUnique(arr1, arr2));
[ 2, 4, 5, 3, 7, 8, 9, 1, 6 ]
Using filter() with indexOf()
This approach concatenates arrays first, then filters duplicates:
const arr1 = [2, 4, 5, 3, 7, 8, 9];
const arr2 = [1, 4, 5, 2, 3, 7, 6];
const mergeWithFilter = (first, second) => {
const combined = [...first, ...second];
return combined.filter((item, index) => combined.indexOf(item) === index);
};
console.log(mergeWithFilter(arr1, arr2));
[ 2, 4, 5, 3, 7, 8, 9, 1, 6 ]
Traditional Loop Approach
A manual implementation using loops and includes() method:
const arr1 = [2, 4, 5, 3, 7, 8, 9];
const arr2 = [1, 4, 5, 2, 3, 7, 6];
const mergeArrays = (first, second) => {
const res = [];
// Add all elements from first array
for (let i = 0; i
[ 2, 4, 5, 3, 7, 8, 9, 1, 6 ]
Comparison
| Method | Performance | Readability | ES6 Support |
|---|---|---|---|
| Set + Spread | Excellent | Very High | Required |
| filter() + indexOf() | Good | High | Partial |
| Traditional Loop | Slower for large arrays | Medium | Not Required |
Conclusion
The Set with spread operator is the most efficient and readable approach for merging arrays and removing duplicates. Use traditional loops only when ES6 support is not available.
Advertisements
