Skip to content
the poor coder

js combine two arrays

Poor Man
Published
Reading time
2 min read

Combining two arrays in JavaScript is a very common task. There are several ways to do this, depending on what you need.

Text

// The most basic way to merge two arrays is to use the concat() method.
var arr1 = [1, 2, 3];
var arr2 = [4, 5, 6];

var arr3 = arr1.concat(arr2);

console.log(arr3); // Output: [1, 2, 3, 4, 5, 6]
        

This method will add the elements of one array to the end of another array, creating a new array. It is important to remember that this method does not mutate the arrays but rather creates a new array which can be stored in a variable like in the above example.

Text

// Another way to merge two arrays is using the spread operator.
var arr4 = [1, 2, 3];
var arr5 = [4, 5, 6];

var arr6 = [...arr4, ...arr5];

console.log(arr6); // Output: [1, 2, 3, 4, 5, 6]
        

The spread operator allows us to expand an array into single elements. This creates a new array which contains all elements from both of the arrays. This method also does not mutate either of the arrays, but rather creates a new array. Finally, you can use the array.push() method. This method will add the elements of one array to the end of another array, mutating the first array. It is important to note that this method will mutate the first array.

Text

// The push() method will mutate the first array.
var arr7 = [1, 2, 3];
var arr8 = [4, 5, 6];

arr7.push(...arr8);

console.log(arr7); // Output: [1, 2, 3, 4, 5, 6]
        

So, depending on your needs, there are several different ways to combine two arrays in JavaScript. Firstly, you can use the concat() method to create a new array which contains all elements from both of the arrays. Secondly, you can use the spread operator to create a new array which contains all elements from both of the arrays. Finally, you can use the array.push() method to add the elements of one array to the end of another array, mutating the first array.

Keep going

2023

how to sort an array

How to Sort an Array If you have an array and you want to order its elements in a specific way, you need to use a sorting algorithm. There are several sorting algorithms available, but two of the most commonly used are…

javascript2 min read
2023

jquery mobile or desktop

jQuery Mobile or Desktop? As a web developer, I have had some experience with both jQuery Mobile and jQuery Desktop. Both frameworks have their pros and cons, and which one to use really depends on the specific project…

javascript1 min read
2023

node.js folder structure

Node.js Folder Structure If you are new to Node.js, it can be daunting to create a folder structure that will work for your project. The structure you choose will depend on the size and complexity of your project. Here…

javascript1 min read
ESC