# Merging and rectifying arrays in JavaScript

JavascriptWeb DevelopmentFront End Technology

## Problem

We are required to write a JavaScript function that takes in two arrays of numbers, arr1 and arr2, as the first and the second arguments.

Our function should merge the elements of both these arrays into a new array and if upon merging or before merging there exists any duplicates, we should delete the excess duplicates so that only one copy of each element is present in the merged array.

The order here is not so important but the frequency of elements (which should be 1 for each element) is important.

For example, if the input to the function is −

onst arr1 = [6, 5, 2, 1, 8];
const arr2 = [3, 4, 6, 8, 9];

Then the output should be −

const output = [6, 5, 2, 1, 8, 3, 4, 9];

## Example

Following is the code −

Live Demo

const arr1 = [6, 5, 2, 1, 8];
const arr2 = [3, 4, 6, 8, 9];
const mergeAndRectify = (arr1 = [], arr2) => {
const { length: len1 } = arr1;
const { length: len2 } = arr2;
const res = [];
let curr = 0;
for(let i = 0; i < len1+len2; i++){
if(i >= len1){
curr = i - len1;
if(!res.includes(arr1[curr])){
res.push(arr1[curr]);
};
}else{
curr = i;
if(!res.includes(arr2[curr])){
res.push(arr2[curr]);
};
};
};
return res;
};
console.log(mergeAndRectify(arr1, arr2));

## Output

Following is the console output −

[ 3, 4, 6, 8, 9, 5, 2, 1 ]
Updated on 21-Apr-2021 11:50:24