15 1 0 4000 1 https://codeblock.co.za 300 true 0
How to Merge Two or More Arrays in JavaScript

How to Merge Two or More Arrays in JavaScript

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 2021? Please let me know in the comments below.

Was This Helpful?

Create a Lightbox Photo Gallery With JQuery
Previous Post
Create a Lightbox Photo Gallery With JQuery
Make Your HTML Buttons More Attractive With These CSS Animations
Next Post
Make Your HTML Buttons More Attractive With These CSS Animations

0 Comments

Leave a Reply