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
Add two array keeping duplicates only once - JavaScript
When working with two arrays, you often need to merge them while keeping only unique values. This operation combines arrays and removes duplicates in a single step.
const arr1 = [2, 4, 5, 3, 7, 8, 9]; const arr2 = [1, 4, 5, 2, 3, 7, 6];
We need to write a JavaScript function that takes two arrays and returns a new array with all duplicates removed (each element appears only once).
Using Set with Spread Operator (Recommended)
The most efficient approach uses ES6 Set to automatically remove duplicates:
const arr1 = [2, 4, 5, 3, 7, 8, 9];
const arr2 = [1, 4, 5, 2, 3, 7, 6];
const mergeUniqueArrays = (first, second) => {
return [...new Set([...first, ...second])];
};
console.log(mergeUniqueArrays(arr1, arr2));
[ 2, 4, 5, 3, 7, 8, 9, 1, 6 ]
Using includes() Method
A more traditional approach using array methods:
const arr1 = [2, 4, 5, 3, 7, 8, 9];
const arr2 = [1, 4, 5, 2, 3, 7, 6];
const mergeArrays = (first, second) => {
const combined = [...first, ...second];
const result = [];
for (let item of combined) {
if (!result.includes(item)) {
result.push(item);
}
}
return result;
};
console.log(mergeArrays(arr1, arr2));
[ 2, 4, 5, 3, 7, 8, 9, 1, 6 ]
Using filter() with indexOf()
Using array methods to filter duplicates based on first occurrence:
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 ]
Comparison
| Method | Performance | Readability | Browser Support |
|---|---|---|---|
| Set + Spread | Best | Excellent | ES6+ |
| includes() | Good | Good | ES2016+ |
| filter() + indexOf() | Good | Good | ES5+ |
Key Points
- Set automatically removes duplicates when creating the collection
- The spread operator (...) converts Set back to array
- Order is preserved based on first occurrence
- All methods work with any data type, not just numbers
Conclusion
Use the Set with spread operator approach for the best performance and cleanest code. For older browser support, the filter() with indexOf() method is a reliable alternative.
Advertisements
