Concatenating variable number of arrays into one - JavaScript


We are required to write a JavaScript function that takes in any number of JavaScript arrays and returns one single array with all the values from input arrays concatenated into it.

For example − If the input arrays are −

[1, 5], [44, 67, 3], [2, 5], [7], [4], [3, 7], [6]

Then the output should be −

const output = [1, 5, 44, 67, 3, 2, 5, 7, 4, 3, 7, 6];

Example

Following is the code −

const a = [1, 5], b = [44, 67, 3], c = [2, 5], d = [7], e = [4], f = [3,
7], g = [6];
const concatArrays = (...arr) => {
   const res = arr.reduce((acc, val) => {
      return acc.concat(...val);
   }, []);
   return res;
};
console.log(concatArrays(a, b, c, d, e, f, g));

Output

Following is the output in the console −

[
   1, 5, 44, 67, 3,
   2, 5,  7,  4, 3,
   7, 6
]

Updated on: 16-Sep-2020

384 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements