69

We all know you can do:

let arr1 = [1,2,3];
let arr2 = [3,4,5];
let arr3 = [...arr1, ...arr2]; // [1,2,3,3,4,5]

But how do you make this dynamic to concat N arrays?

6
  • you could store the dynamic arrays in an array ... Commented Apr 17, 2017 at 17:03
  • 1
    or an object with arrays as values. Impossible to iterate unknown qty of individual variables Commented Apr 17, 2017 at 17:03
  • 6
    Why do you have to use the spread operator? The concat method still works... Commented Apr 17, 2017 at 17:04
  • Does Array.prototype.concat not do it for you? developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… Commented Apr 17, 2017 at 17:04
  • Uh, ohh so ES5ify Function.prototype.call.bind(Array.prototype.concat) :) Commented Apr 17, 2017 at 17:11

10 Answers 10

91

One option is to use reduce:

let arrs = [[1, 2], [3, 4], [5, 6]];
arrs.reduce((a, b) => [...a, ...b], []);

Of course, this is a slow solution (quadratic time). Alternatively, if you can use Lodash, _.flatten does exactly what you want, and does it more efficiently (linear time).

EDIT

Or, adapted from Xotic750's comment below,

[].concat(...arrs);

Which should be efficient (linear time).

Sign up to request clarification or add additional context in comments.

4 Comments

One you have your arrays in an array, you could then. Array.prototype.concat.apply([], arr) Though this isn't using the spread operator any more.
@Xotic750 Nice, but you can do that using the spread operator! See my edit.
Note that in typescript you need to force the empty array to be typed if you want the return value to be number[] and not any[] (eg. ([] as number[]).concat(...arrs))
Are there any new other solutions for this?
22

Another option could be:

const nArrays = [
  [1, 2, 3, 4, 5],
  [6, 7, 8, 9],
  [10, 11]
];
const flattened = [].concat(...nArrays);
console.log(flattened)

1 Comment

As of ES2019, you can just use nArrays.flat()
16

let fruits = ["apples", "bananas", "pears"];
let vegetables = ["corn", "potatoes", "carrots"];

let produce = [...fruits, ...vegetables];


console.log(produce);

1 Comment

This given code is exactly same as the given question. It is not an answer for making dynamiclly concat solution for N arrays.
4

Best option is to use FlatMap, which helps us to conact multiple arrays into one single array.

Example:

let arrs = [[1, 2], [3, 4], [5, 6]];
arrs.flatMap(a => a);

result will be

> (6) [1, 2, 3, 4, 5, 6]

Happy Coding...

Comments

3

Following solution works for me (spread operator in ES6):

let array = ['my','solution','works'];
let newArray = [];
let newArray2 = [];
newArray.push(...array); //adding to same array
newArray2.push([...array]); //adding as child/leaf/sub-array
console.log(newArray);
console.log(newArray2);

Comments

2

You can't do that with spread syntax alone, as spread syntax requires you to know how many arrays you are concatenating in advance. However, you could write the following function:

function concatN(...arguments) {
    let accumulator = [];
    for(let arg = 0; arg < arguments.length; arg = arg + 1) {
        accumulator = [...accumulator, ...arguments[arg]];
    }
    return accumulator;
}

It probably won't be very efficient, though (repeated use of spread syntax is O(n²)). Using Array.prototype.concatwould be better. You can just do:

[].concat(all, of, your, arrays);

Comments

2

You can use spread element within for..of loop to concatenate array values to a single array

let arr1 = [1,2,3];
let arr2 = [3,4,5];
let arr3 = [];

for (let arr of [arr1, arr2 /* , arrN */]) arr3.push(...arr);

console.log(arr3);

Comments

1

You could use a recursive function and Array.prototype.concat

const concatN = (x,...xs) =>
  x === undefined ? [] : x.concat(concatN(...xs))

console.log(concatN([1,2,3], [4,5,6], [7,8,9]))
// [1,2,3,4,5,6,7,8,9]

You can do the same thing using reduce and Array.prototype.concat. This is similar to the accepted answer but doesn't senselessly use spread syntax where x.concat(y) is perfectly acceptable (and likely heaps faster) in this case

const concatN = (...xs) =>
  xs.reduce((x,y) => x.concat(y), [])

console.log(concatN([1,2,3], [4,5,6], [7,8,9]))
// [1,2,3,4,5,6,7,8,9]

Comments

1

We can resolve using es6 following way

function mergeTwo(arr1, arr2) {
  let result = [...arr1, ...arr2];
  return result.sort((a,b) => a-b);
}

Comments

0

let arr1 = [1,2,3];
let arr2 = [3,4,5];
let arrs = [arr1, arr2].flat(); // [1,2,3,3,4,5]

console.log(arrs);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.