Oftentimes, we need to combine multiple arrays into one array. With multiple arrays, combining them is pain without some help from JavaScript’s standard libraries. With ES6, there’s also the spread syntax to help us combine arrays.
There are a few ways to merge arrays in JavaScript.
Array.concat
We can all Array.concat
on an array to combine 2 arrays and return the new one. For example:
const a = [1,2,3];
const b = [4,5];
const c = a.concat(b) // [1,2,3,4,5]
It also works with multiple arrays. You can pass in as many arrays as you want in the arguments of the concat
function. For example:
const a = [1,2,3];
const b = [4,5];
const c = [6,7,8];
const d = a.concat(b, c) // [1,2,3,4,5,6,7]
Array.push
We can push elements of one array into another.
const a = [1,2,3];
const b = [4,5];
let c = Object.assign([], a);
for (let i = 0; i < b.length; i++){
c.push(b[i]);
}
console.log(c); // [1,2,3,4,5]
What we did is make a copy of a
and assigned it to c
, then pushed the elements of b
by looping through it and adding them to the end of c
.
You can use the apply
function available with all objects to combine 2 arrays. For example:
const a = [1,2];
const b = [3,4];
a.push.apply(a, b);
console.log(a); // [1,2,3,4];
Spread Operator
With ES6 or later, we can use the spread operator to spread the items from another array into a new array by doing the following:
const a = [1,2,3];
const b = [4,5];
const c = [...a, ...b];
console.log(c); // [1,2,3,4,5]