The concat method

The concat() method is used to combine the elements of two or more array and return a new array containing all of the elements.

var Motorbikes = new Array("Yamaha" , "Suzuki");
var Cars = new Array("BMW" , "Audi");

var Autovehicles = Motorbikes.concat(Cars);
document.write(Autovehicles);

First I have created two arrays, each containing two elements. Then, using concat() method, I combined the elements of the two arrays into one new array named Autovehicles.

First in the new array are the elements of the Motorbikes array followed by the element of the Cars array. If you take a look at the code you will know why.

In the following example the elements of the Cars array are first then followed by the elements of the Motorbikes array.

var Motorbikes = new Array("Yamaha" , "Suzuki");
var Cars = new Array("BMW" , "Audi");

var Autovehicles_2 = Cars.concat(Motorbikes);
document.write(Autovehicles_2);

You use the array of which elements you want to appear first in the new array to call the concast() method and send the second array as parameter so you get its elements in the new array after the elements of the array that called the concat() method.

If you combine three or more arrays then the elements in the new array are ordered as follow:

  • The elements of the array used to call the concat() method.
  • The elements of the arrays that are sent as parameters in the order in which they are sent.
var Motorbikes = new Array("Yamaha" , "Suzuki");
var Cars = new Array("BMW" , "Audi");
var Planes = new Array("Boeing" , "Airbus");

var Autovehicles = Motorbikes.concat(Cars , Planes);
document.write(Autovehicles);

The output of the above code will be “Yamaha,Suzuki,BMW,Audi,Boeing,Airbus”.

Leave a Reply