Joining two Arrays in Javascript


There are two ways to join 2 arrays in Javascript. If you want to get a new array and not want to disturb the existing arrays while joining the two arrays then you should use the concat method as follows − 

Example

let arr1 = [1, 2, 3, 4];
let arr2 = [5, 6, 7, 8];
let arr3 = arr1.concat(arr2);
console.log(arr1);
console.log(arr2);
console.log(arr3);

Output

This will give the output −

[1, 2, 3, 4]
[5, 6, 7, 8]
[1, 2, 3, 4, 5, 6, 7, 8]

Note that the existing arrays were not modified. If you want to join in place, you'll need to use the push method with apply. The apply function unpacks values from an array and passes it to the function it is applied to as arguments. For example, 

Example

let arr1 = [1, 2, 3, 4];
let arr2 = [5, 6, 7, 8];
arr1.push.apply(arr2);
console.log(arr1);
console.log(arr2);

Output

This will give the output −

[1, 2, 3, 4, 5, 6, 7, 8]
[5, 6, 7, 8]

Note that here the first array was changed itself.

Sharon Christine
Sharon Christine

An investment in knowledge pays the best interest

Updated on: 15-Jun-2020

145 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements