Bikshu s
Bikshu s

Reputation: 397

How to concat multiple array into single array

How to concat all this array into a single array:

[Array(10), Array(10), Array(10), Array(10), Array(10), Array(10), Array(10), Array(2)]

Upvotes: 1

Views: 2007

Answers (3)

gurvinder372
gurvinder372

Reputation: 68393

Use reduce and concat

var output = arr.reduce( (a, c) => a.concat(c), []); //assuming arr is the input array

Edit

As @TJ mentioned in his comment, that above solution will create some intermediate arrays along the way, you can try (concat without spread)

var output = [].concat.apply([], arr);

or

var output = Array.prototype.concat.apply([], arr); //avoiding usage of another unnecessary array `[]`

Upvotes: 4

Faly
Faly

Reputation: 13346

You can use ES6's spread:

var arrays = [[1, 2], [3, 4], [5, 6]];
var res = [].concat(...arrays);
console.log(res);

Upvotes: 4

Jeremy M.
Jeremy M.

Reputation: 1164

var array1 = ['a', 'b', 'c'];
var array2 = ['d', 'e', 'f'];

console.log(array1.concat(array2));
// expected output: Array ["a", "b", "c", "d", "e", "f"]

If you have an array of array you can do like so :

let bigArray = new Array();

arrayOfArray.forEach((arr) => {
    bigArray.concat(arr);
});

Upvotes: 0

Related Questions