Merging nested arrays to form 1-d array in JavaScript

JavascriptWeb DevelopmentFront End Technology

Problem

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

Our function should create and return a third array that contains all the elements of arr1 and arr2 but flattened to single dimension

For example, if the input to the function is −

const arr1 = [
1, [
2, [
4, 5, [
6
]
]
]
];
const arr2 = [
11, 12, [
16, 18, [
19, 21, [
23
]
]
]
];

Then the output should be −

const output = [1, 2, 4, 5, 6, 11, 12, 16, 18, 19, 21, 23];

Example

Following is the code −

Live Demo

const arr1 = [
1, [
2, [
4, 5, [
6
]
]
]
];
const arr2 = [
11, 12, [
16, 18, [
19, 21, [
23
]
]
]
];
const flattenAndMerge = (arr1 = [], arr2 = []) => {
const res = [];

const flatten = (arr = []) => {
for(let i = 0; i < arr.length; i++){
if(Array.isArray(arr[i])){

flatten(arr[i]);
}else if(typeof arr[i] === 'number'){
res.push(arr[i])
};
};
};
flatten(arr1);
flatten(arr2);
return res;
};
console.log(flattenAndMerge(arr1, arr2));

Output

Following is the console output −

[
1, 2, 4, 5, 6,
11, 12, 16, 18, 19,
21, 23
]
Published on 21-Apr-2021 12:06:51