WEB TUTORIALS
PRACTICE EXAMPLES
HTML REFERENCES
CSS REFERENCES
PHP REFERENCES

How to Merge Two Arrays in JavaScript

Topic: JavaScript / jQueryPrev|Next

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]

See the tutorial on JavaScript Arrays to learn more about creating and manipulating arrays.


Related FAQ

Here are some more FAQ related to this topic:

Bootstrap UI Design Templates Property Marvels - A Leading Real Estate Portal for Premium Properties