How to Merge Two or More Arrays in JavaScript
11th September 2020
0 Comments
Merging arrays can make handling certain tasks and data much easier. If you need to merge (or concatenate) two arrays into one array, you can use the JavaScript concat() method. Let’s take a look at the syntax.
let fruits = ['apples', 'bananas', 'pears', 'grapes'];
let veggies = ['carrots', 'potatoes', 'broccoli', 'peas'];
let food = fruits.concat(veggies);
In this example the following will be output if we console.log food:
(8) ['apples', 'bananas', 'pears', 'grapes', 'carrots', 'potatoes', 'broccoli', 'peas']
You can combine multiple arrays by separating additional arrays with a comma.
let fruits = ['apples', 'bananas', 'pears', 'grapes'];
let veggies = ['carrots', 'potatoes', 'broccoli', 'peas'];
let proteins = ['chicken', 'fish', 'beef'];
let starches = ['bread', 'pasta', 'rice'];
let food = fruits.concat(veggies, proteins, starches);
This will output:
(14) ['apples', 'bananas', 'pears', 'grapes', 'carrots', 'potatoes', 'broccoli', 'peas', 'chicken', 'fish', 'beef', 'bread', 'pasta', 'rice']
Keep in mind that the concat() method creates a new array of the merged arrays and leaves the source arrays intact.
Is this still valid in 2024? Please let me know in the comments below.
Was This Helpful?
If this post has helped you, please let me know. Your feedback will be highly appreciated and will help me build better content.