Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

javascript
array
merge
communitycreator

How to merge arrays in JavaScript

Programming Bytes

In this shot, we will learn different ways to merge multiple arrays into a single array.

1. Using spread operator

The spread operator expands/unpacks an iterable object arr that we can use to merge multiple arrays into a single array.

let hero = ['Rajini', 'Kamal', 'Fahad'];
let villan = ['Vijay seathupathi', 'Nasar'];

let heroicVillan = [...hero, ...villan];
console.log(heroicVillan);

In the code above, we have used the spread operator(...) to merge the multiple arrays into a new array.

2. Using concat method

The concat method will merge two or more arrays into a single array and return a new array.

var array1 = [1,2,3,4,5]
var array2 = [6,7,8,9,10];
var array3 = [11,12,13];

console.log("Merging array by [].concat(array1, array2, array3 )")
var mergedArray = [].concat(array1, array2, array3);
console.log("Merged Array", mergedArray);

// another way
console.log("\nMerging array by array1.concat(array2, array3) ")
mergedArray = array1.concat(array2, array3);
console.log("Merged Array", mergedArray);

In the code above, we have merged three arrays into an empty array. This will result in merging multiple arrays into a new array.

3. Using push with the spread operator

We can use a spread operator, which will expand all the iterable elements, and then add the expanded element to an array using push method.

function merge(...arrays) {
    let newArray = [];
    for(let i = 0; i < arrays.length; i++) {
        newArray.push(...arrays[i]);
    }
    return newArray;
}

console.log(merge([1,2,3], [4,5,6], [7,8,9]))

In the code above, we used the rest parameter in the function to receive any number of arguments. Then, we looped all the arguments and expanded the array using the spread operator. Finally, we pushed the expanded elements to the newArray.

RELATED TAGS

javascript
array
merge
communitycreator
RELATED COURSES

View all Courses

Keep Exploring