# Add two array keeping duplicates only once - JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

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
]
Published on 15-Sep-2020 09:16:24