Yogesh Chauhan's Blog

How to merge arrays in JavaScript?

in JavaScript on November 16, 2020

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.


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. 


Merging 2 Arrays

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

// [ '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);

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

💡 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);


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

Merging 3 Arrays

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

// [ '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");

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

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

Most Read

#1 How to check if radio button is checked or not using JavaScript? #2 How to add Read More Read Less Button using JavaScript? #3 Solution to “TypeError: ‘x’ is not iterable” in Angular 9 #4 How to uninstall Cocoapods from the Mac OS? #5 PHP Login System using PDO Part 1: Create User Registration Page #6 How to Use SQL MAX() Function with Dates?

Recently Posted

#Jan 17 4 advanced ways to search Colleague #Jan 16 Colleague UI Basics: The Search Area #Jan 16 Colleague UI Basics: The Context Area #Jan 16 Colleague UI Basics: Accessing the user interface #Jan 14 How to display a student’s individual transcript in Colleague? #Jan 11 How to install PuTTY on a MacOS?
You might also like these
The Sort and Compare Functions in JavaScriptJavaScriptA list of wp-cli commands to use via SSHWordPressConditional operator in JavaScript (aka ternary operator)JavaScriptSQL ANY OperatorSQL/MySQLAND, OR and NOT boolean operators in Envision BasicEnvision BasicHow to create a Star Ratings using CSS?CSS