Please note, this is a STATIC archive of website www.tutorialrepublic.com from 10 Sep 2022, cach3.com does not collect or store any user information, there is no "phishing" involved.
WEB TUTORIALS
PRACTICE EXAMPLES
HTML REFERENCES
CSS REFERENCES
PHP REFERENCES
Advertisements

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:

Advertisements
Bootstrap UI Design Templates