Q:

How to Merge Two Arrays in JavaScript

0

How to Merge Two Arrays in JavaScript

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Use the concat() Method

You can simply use the concat() method to merge two or more JavaScript arrays. This method does not change the existing arrays, but instead returns a new array.

Let's try out the following example to understand how it basically works:

// Sample arrays
var array1 = ["Red", "Green", "Blue"];
var array2 = ["Apple", "Kiwi"];

// Concatenating the arrays
var result = array1.concat(array2);
console.log(result); // Prints: ["Red", "Green", "Blue", "Apple", "Kiwi"]

The following example shows how to use concat() method to merge more than two arrays:

// Sample arrays
var array1 = [1, 2, 3];
var array2 = [4, 5, 6];
var array3 = [7, 8, 9];

// Concatenating the arrays
var result = array1.concat(array2, array3);
console.log(result); // Prints: [1, 2, 3, 4, 5, 6, 7, 8, 9]

Alternatively, you can also use the spread operator (...) introduced in JavaScript ES6 to merge two or more arrays, as demonstrated in the following example:

// Sample arrays
var array1 = ["a", "b", "c"];
var array2 = [1, 2, 3];

// Concatenating the arrays
var result = [...array1, ...array2];
console.log(result); // Prints: ["a", "b", "c", 1, 2, 3]

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

JavaScript / jQuery Frequently Asked Questions

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
How to Check If a Value is an Object in JavaScript... >>
<< How to Count Number of Rows in a Table Using jQuer...