JavaScript Array concat: Merge Arrays

Summary: in this tutorial, you will learn how to use the JavaScript Array concat() method to merge two or more arrays into a single array.

To merge two or more arrays, you use the concat() method of an Array object. The concat() method returns a new array and doesn’t change the original arrays. For example:

let odds = [1,3,5];
let evens = [2,4,6];
// merge odds and evens array
let combined = odds.concat(evens);

console.log('Result:', combined);
console.log('Odds:', odds);Code language: JavaScript (javascript)

Output:

Result: [ 1, 3, 5, 2, 4, 6 ]
Odds: [ 1, 3, 5 ]Code language: CSS (css)

In this example, we have two arrays: odds and evens. We call the concat() method of the odds array method to merge elements of the two arrays. The elements of the second array are appended to the elements of the first array.

Similarly, you can call the concat() method on an empty array denoted by ([]):

let odds = [1,3,5];
let evens = [2,4,6];
// merge odds and evens array
let combined = [].concat(odds, evens);

console.log(combined);Code language: JavaScript (javascript)

Output:

[ 1, 3, 5, 2, 4, 6 ]Code language: JSON / JSON with Comments (json)

The concat() method allows you to merge more than two arrays as shown in the following example:

let upper  = ['A','B','C'];
let lower  = ['a','b','c'];
let digits = [1,2,3];
let alphanumerics = upper.concat(lower, digits);Code language: JavaScript (javascript)

Output:

['A', 'B', 'C', 'a',  'b', 'c', 1,   2,  3]Code language: JSON / JSON with Comments (json)

In this example, we merge the three arrays: upper, lower, and digits.

When you don’t pass any argument into the concat() method, it simply clones the array and returns it:

let colors = ['red','green','blue'];
let rgb = colors.concat();
console.log(rgb);Code language: JavaScript (javascript)

Output:

[ 'red', 'green', 'blue' ]Code language: JSON / JSON with Comments (json)

If you pass values that are not arrays, into the concat() method, the method will appends each value to the end of the result array:

let rgb = ['red','green','blue'];
let moreColors = rgb.concat('yellow','magento');
console.log(moreColors);Code language: JavaScript (javascript)

Output:

[ 'red', 'green', 'blue', 'yellow', 'magento' ]Code language: JSON / JSON with Comments (json)

In ES6, you can use spread operator to merge multiple arrays as follows:

let odds = [1,3,5];
let evens = [2,4,6];
let combined = [...odds, ...evens];
console.log(combined);Code language: JavaScript (javascript)

Output:

[ 1, 3, 5, 2, 4, 6 ]Code language: JSON / JSON with Comments (json)

In this tutorial, you have learned two ways to merge multiple arrays into a single array by using the JavaScript Array concat() method and spread operator.

Was this tutorial helpful ?