Ivan Hreskiv
Ivan Hreskiv

Reputation: 1075

Join arrays expression in ECMAScript 2016

I am new to JavaScript. I need to write simple script which should join several arrays into one. I found this example:

var arr1 = ['a', 'b', 'c'];
var arr2 = ['d', 'e', 'f'];

var arr3 = arr1.concat(arr2);

But I have more than two arrays. Is it possible to concat several arrays in one expression?

Upvotes: 0

Views: 67

Answers (3)

Karthik RP
Karthik RP

Reputation: 1078

var arr1 = ['a', 'b', 'c'];
var arr2 = ['d', 'e', 'f'];
var arr3 = ['g', 'h', 'i'];
var arr4 = ['j', 'k', 'l'];

var arr5 = Array.prototype.concat.apply(arr1, [arr2, arr3, arr4]);
console.log(arr5);

By this means you can concat n number of arrays. Just add more arrays after arr4.


If you have array of arrays, Something like this,

 var arr1 = [['a', 'b', 'c'], ['d', 'e', 'f'], ['g', 'h', 'i'], ['j', 'k', 'l']]

You can use spread,

var arr2 = Array.prototype.concat(...arr1);
console.log(arr2);

Upvotes: 1

Charlie
Charlie

Reputation: 23798

You can supply multiple arrays to Array.prototype.concat function.

var arr1 = [1, 2, 3];
var arr2 = [4, 5, 6];
var arr3 = [7, 8, 9];

arr1.concat(arr2, arr3);     //[1, 2, 3, 4, 5, 6, 7, 8, 9]

Upvotes: 1

M0nst3R
M0nst3R

Reputation: 5283

The Array method concat() returns the concatenation result which you can in turn use for your next concatenation.

If you have a static list of arrays (3 for example):

let result = arr1.concat(arr2).concat(arr3);

If you have an array of arrays:

let result = [];
for (let i = 0; i < bigArr.length; i++) {
    result = result.concat(bigArr[i]);
}

Upvotes: 0

Related Questions