We can use concat() method to merge one or more than one arrays.

The concat() method creates a new array by merging, or concatenating, existing arrays.

Syntax


const array2 = array1.concat(arrays / values)

The concat() method creates a new array consisting of the elements in the object on which it is called.

It keeps adding the arrays elements in the same order as the arrays in arguments OR it values in the same order as arguments. 

Examples

Merging 2 Arrays


var names1 = ["Yogesh", "John"];
var names2 = ["Yogi", "Jonny"];
var names = names1.concat(names2);
console.log(names);

// [ 'Yogesh', 'John', 'Yogi', 'Jonny' ]

You can concat strings and numbers as well.


var names1 = ["Yogesh", "John"];
var names2 = [2, 3, 4];
var names = names1.concat(names2);
console.log(names);

// [ 'Yogesh', 'John', 2, 3, 4 ]

enlightened concat() method change the existing arrays but returns a new array.

Merge Nested Arrays


const array1 = [["Yogesh"]];
const array2 = ["Jon", [2]];

const array = array1.concat(array2);

console.log(array);

// [ [ 'Yogesh' ], 'Jon', [ 2 ] ]

Merging 3 Arrays


var names1 = ["Yogesh", "John"];
var names2 = ["Yogi", "Jonny"];
var names3 = ["Yog", "Jon"];
var names = names1.concat(names2, names3);
console.log(names);

// [ 'Yogesh', 'John', 'Yogi', 'Jonny', 'Yog', 'Jon' ]

As we can see, all we need to do is just pas another array in the arguments. We can pass any number of arguments.

Passing a string as an argument


var names1 = ["Yogesh", "John"];
var names = names1.concat("Yog");
console.log(names);

// [ 'Yogesh', 'John', 'Yog' ]

It works like push() method. Isn't it? JavaScript is full of surprises. surprise

0 Comments

Leave a reply

Your email address will not be published. required fields are marked *