3 Ways to Merge Arrays in JavaScript — Codeymaze

CodeyMaze
2 min readJul 13, 2024

--

In JavaScript, an array is a data structure that allows you to store multiple values in a single variable. Arrays can hold elements of any type, including numbers, strings, objects, and even other arrays.

You can create arrays in several ways. The most common is using square brackets[]

In this post, we will list down 3 ways to merge arrays in JavaScript -

Merge using the spread operator

The spread operator is used to spread out elements of an array or object. Spread operator is denoted by three dots […]

This is the easiest and fastest way to merge arrays. It lets you merge 2 or even more than 2 arrays at once. The order of array elements will be in the same order in which it is merged.

let arr1 = ['red','yellow'];
let arr2 = ['blue','green'];
let mergedArr = [...arr1, ...arr2];

console.log(mergedArr); // Output: ['red','yellow','blue','green']

Merge using array.concat()

The array.concat() method is used to merge two or more arrays. This method does not update the existing array but instead returns new array. so if you want to keep your original array intact then you may consider using this to merge arrays.

Let’s see how to concatenate three arrays using array.concat()

let arr1 = ['red','yellow'];
let arr2 = ['blue','green'];
let mergedArr = arr1.concat(arr2);

console.log(mergedArr); // Output: ['red','yellow','blue','green']

Read full article on https://codeymaze.com/ways-to-merge-arrays-in-javascript/

Originally published at https://codeymaze.com on July 13, 2024.

--

--

CodeyMaze
CodeyMaze

Written by CodeyMaze

Crafting Solutions Through Code & Words https://codeymaze.com Feel free to follow me :)

No responses yet