Computer >> Computer tutorials >  >> Programming >> Javascript

How to add two arrays into a new array in JavaScript?


Let’s say the following is our first array −

var firstArray=["John","David","Bob","Mike"];

Following is our second array −

var secondArray=["Chris","Adam","James","Carol"];

To add the above two arrays into a new array, use concat().

Example

Following is the code −

var firstArray=["John","David","Bob","Mike"];
var secondArray=["Chris","Adam","James","Carol"];
var thirdArray=firstArray.concat(secondArray);
console.log("First Array value=");
console.log(firstArray);
console.log("Second Array value=");
console.log(secondArray);
console.log("Third Array value=");
console.log(thirdArray);

To run the above program, you need to use the following command −

node fileName.js.

Here, my file name is demo249.js.

Output

This will produce the following output on console −

PS C:\Users\Amit\javascript-code> node demo249.js
First Array value=
[ 'John', 'David', 'Bob', 'Mike' ]
Second Array value=
[ 'Chris', 'Adam', 'James', 'Carol' ]
Third Array value=
[
   'John',  'David',
   'Bob',   'Mike',
   'Chris', 'Adam',
   'James', 'Carol'
]