Skip to content

How to merge two arrays in JavaScript

Learn how to merge two arrays together in JavaScript. There are various ways you can achieve it. In this post, we will go through some of the ways to merge arrays.

Array.concat

The concat() method is used to join two or more arrays. This method does not change the existing arrays, but returns a new array, containing the values of the joined arrays.

let arr1 = [0, 2, 4, 6, 8];
let arr2 = [1, 3, 5, 7, 9];
let all = arr1.concat(arr2);

ES6 Spread Syntax

Spread syntax lets an iterable such as an array expression or string to be expanded in places where zero or more arguments (for function calls) or elements (for array literals) are expected, or an object expression to be expanded in places where zero or more key-value pairs (for object literals) are expected. This is applicable when creating a new array literal.

let arr1 = [0, 2, 4, 6, 8];
let arr2 = [1, 3, 5, 7, 9];
let all = [...arr1, ...arr2];

Array.push

The push() method adds new items to the end of an array, and returns the new length. This method changes the length of the array.

let arr1 = [0, 2, 4, 6, 8];
let arr2 = [1, 3, 5, 7, 9];
let all = arr1.push(...arr2);

Array.unshift

The unshift() method adds new items to the beginning of an array, and returns the new length. This method changes the length of the array.

let arr1 = [0, 2, 4, 6, 8];
let arr2 = [1, 3, 5, 7, 9];
let all = arr2.unshift(...arr1);

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.