

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Merge and remove duplicates in JavaScript Array
Suppose, we have two arrays of literals like these −
const arr1 = [2, 4, 5, 3, 7, 8, 9]; const arr2 = [1, 4, 5, 2, 3, 7, 6];
We are required to write a JavaScript function that takes in two such arrays and returns a new array with all the duplicates removed (should appear only once).
Example
The code for this will be −
const arr1 = [2, 4, 5, 3, 7, 8, 9]; const arr2 = [1, 4, 5, 2, 3, 7, 6]; const mergeArrays = (first, second) => { const { length: l1 } = first; const { length: l2 } = second; const res = []; let temp = 0; for(let i = 0; i < l1+l2; i++){ if(i >= l1){ temp = i - l1; if(!res.includes(first[temp])){ res.push(first[temp]); }; }else{ temp = i; if(!res.includes(second[temp])){ res.push(second[temp]); }; }; }; return res; }; console.log(mergeArrays(arr1, arr2));
Output
The output in the console −
[ 1, 4, 5, 2, 3, 7, 6, 8, 9 ]
- Related Questions & Answers
- Remove duplicates and map an array in JavaScript
- Remove array duplicates by property - JavaScript
- Remove duplicates from a array of objects JavaScript
- Remove duplicates from array with URL values in JavaScript
- Remove Duplicates from Sorted Array in Python
- Remove duplicates from an array keeping its length same in JavaScript
- Remove Duplicates from Sorted Array II in C++
- Counting duplicates and aggregating array of objects in JavaScript
- How do I make an array with unique elements (remove duplicates) - JavaScript?
- The best way to remove duplicates from an array of objects in JavaScript?
- Remove Consecutive Duplicates in Python
- Unique sort (removing duplicates and sorting an array) in JavaScript
- Java Program to Remove Duplicates from an Array List
- Commons including duplicates in array elements in JavaScript
- Merge JSON array date based JavaScript
Advertisements