Best ways to merge two arrays into a single array in JavaScript?

Here are some of the best ways you can use to merge or combine two arrays in javascript :

Concatenation (concat method)

JavaScript
const array1 = [1, 2, 3];
const array2 = [4, 5, 6];
const combinedArray = array1.concat(array2);
// Output: [1, 2, 3, 4, 5, 6]

Spread Operator

JavaScript
const array1 = [1, 2, 3];
const array2 = [4, 5, 6];
const combinedArray = [...array1, ...array2];
// Output: [1, 2, 3, 4, 5, 6]

Array push method

JavaScript
const array1 = [1, 2, 3];
const array2 = [4, 5, 6];
array1.push(...array2);
// Now, array1 contains the combined elements

Array push and apply (for older JavaScript versions)

JavaScript
const array1 = [1, 2, 3];
const array2 = [4, 5, 6];
Array.prototype.push.apply(array1, array2);
// Now, array1 contains the combined elements
// Output: [1, 2, 3, 4, 5, 6]

Using Array.from

JavaScript
const array1 = [1, 2, 3];
const array2 = [4, 5, 6];
const combinedArray = Array.from(array1).concat(array2);
// Output: [1, 2, 3, 4, 5, 6]

Using the Array constructor

JavaScript
const array1 = [1, 2, 3];
const array2 = [4, 5, 6];
const combinedArray = new Array(...array1, ...array2);
// Output: [1, 2, 3, 4, 5, 6]

Using Array.push with a for-loop

JavaScript
const array1 = [1, 2, 3];
const array2 = [4, 5, 6];
for (let i = 0; i < array2.length; i++) {
  array1.push(array2[i]);
}
// Now, array1 contains the combined elements

Leave a Reply

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