DEV Community

Cover image for 5 Ways To Merge Arrays in JavaScript
Roopam Gupta
Roopam Gupta

Posted on

5 Ways To Merge Arrays in JavaScript

First, Using Concat Method

{

    let arr1 = [1, 2, 3];
    let arr2 = [4, 5, 6];

    let merged = [].concat(arr1, arr2);
    console.log(merged);

    // Output :-
    // [1, 2, 3, 4, 5, 6]

}
Enter fullscreen mode Exit fullscreen mode

Second, Using Push Method

{

    let arr1 = [1, 2, 3];
    let arr2 = [4, 5, 6];

    let merged = arr1.push(...arr2);
    console.log(merged);   //  6
    console.log(arr1);     //  [1, 2, 3, 4, 5, 6]

}
Enter fullscreen mode Exit fullscreen mode

Third, Using Spread Operator

{

    let arr1 = [1, 2, 3];
    let arr2 = [4, 5, 6];

    let merged = [...arr1, ...arr2];
    console.log(merged);

    // Output :-
    // [1, 2, 3, 4, 5, 6]

}
Enter fullscreen mode Exit fullscreen mode

Fourth, Using For Loop

{

    const merge = (first, second) => {
        for(let i=0; i<second.length; i++){
            first.push(second[i]);
        }
        return first;
    }

    let merged = merge(merge([1, 2, 3],[4, 5, 6]))
    console.log(merged);

    // Output :-
    // [1, 2, 3, 4, 5, 6]
}
Enter fullscreen mode Exit fullscreen mode

Fifth, Using reduce methods

{

    let arr1 = [1,2,3];
    let arr2 = [4,5,6];

    let merged = arr2.reduce((arr,item) => {
        arr.push(item);
        return arr;
    }, arr1);
    console.log(merged);  //  6
    console.log(arr1);    //  [1,2,3,4,5,6]

}

Enter fullscreen mode Exit fullscreen mode

Also Checkout :

JavaScript Arrow Functions ( easy tutorial )

Top comments (0)