
- Javascript Basics Tutorial
- Javascript - Home
- Javascript - Overview
- Javascript - Syntax
- Javascript - Enabling
- Javascript - Placement
- Javascript - Variables
- Javascript - Operators
- Javascript - If...Else
- Javascript - Switch Case
- Javascript - While Loop
- Javascript - For Loop
- Javascript - For...in
- Javascript - Loop Control
- Javascript - Functions
- Javascript - Events
- Javascript - Cookies
- Javascript - Page Redirect
- Javascript - Dialog Boxes
- Javascript - Void Keyword
- Javascript - Page Printing
- JavaScript Objects
- Javascript - Objects
- Javascript - Number
- Javascript - Boolean
- Javascript - Strings
- Javascript - Arrays
- Javascript - Date
- Javascript - Math
- Javascript - RegExp
- Javascript - HTML DOM
- JavaScript Advanced
- Javascript - Error Handling
- Javascript - Validations
- Javascript - Animation
- Javascript - Multimedia
- Javascript - Debugging
- Javascript - Image Map
- Javascript - Browsers
- JavaScript Useful Resources
- Javascript - Questions And Answers
- Javascript - Quick Guide
- Javascript - Functions
- Javascript - Resources
Add two array keeping duplicates only once - JavaScript
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
Let’s write the code for this function −
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 Articles
- Remove duplicates from an array keeping its length same in JavaScript
- Keeping only alphanumerals in a JavaScript string in JavaScript
- Finding two missing numbers that appears only once and twice respectively in JavaScript
- Program to pick out duplicate only once - JavaScript
- Keeping only redundant words in a string in JavaScript
- Remove array duplicates by property - JavaScript
- Merge and remove duplicates in JavaScript Array
- Remove duplicates from a array of objects JavaScript
- Remove duplicates and map an array in JavaScript
- Commons including duplicates in array elements in JavaScript
- Comparing array elements keeping count in mind in JavaScript
- Remove duplicates from array with URL values in JavaScript
- Counting duplicates and aggregating array of objects in JavaScript
- Matching Only Once in Perl
- Sort an integer array, keeping first in place in JavaScript

Advertisements