WebTuts - seomat.com

Your ultimate destination for comprehensive, easy-to-follow web tutorials.

Several ways to merge two arrays in JavaScript

Merging two arrays in JavaScript is a common operation in programming, often used when you need to combine the contents of multiple arrays into a single array.

There are several ways to merge two arrays in JavaScript. Here are some common methods:

1. Using the spread operator

const array1 = [1, 2, 3];
const array2 = [4, 5, 6];
const mergedArray = [...array1, ...array2];
console.log(mergedArray); // [1, 2, 3, 4, 5, 6]

2. Using the concat() method

const array1 = [1, 2, 3];
const array2 = [4, 5, 6];
const mergedArray = array1.concat(array2);
console.log(mergedArray); // [1, 2, 3, 4, 5, 6]

3. Using the push() method

const array1 = [1, 2, 3];
const array2 = [4, 5, 6];
array2.forEach(element => array1.push(element));
console.log(array1); // [1, 2, 3, 4, 5, 6]

4. Using the push() method with apply()

const array1 = [1, 2, 3];
const array2 = [4, 5, 6];
Array.prototype.push.apply(array1, array2);
console.log(array1); // [1, 2, 3, 4, 5, 6]

5. Using the slice() and push() methods

const array1 = [1, 2, 3];
const array2 = [4, 5, 6];
Array.prototype.push.apply(array1, array2.slice());
console.log(array1); // [1, 2, 3, 4, 5, 6]

6. Using the push() method with the spread operator

const array1 = [1, 2, 3];
const array2 = [4, 5, 6];
array1.push(...array2);
console.log(array1); // [1, 2, 3, 4, 5, 6]

All of these methods will merge the elements of the two arrays into a single array. Choose the method that best suits your needs and coding style.