Merging Collections: Arrays

Bastiaan Dressen
19-01-2017

What are the options for merging arrays in javascript?

Javascript is a really flexible language and it has a lot of built-in functionality for working with collections like arrays and objects. However, for merging arrays it doesn’t have that many options. Actually without moving into workarounds (eg. like iterating over arrays and filling another array with items from the iterated arrays) we really only have a couple of methods. Let’s see a what’s in store for merging arrays.

  1. For merging arrays in ES5 and upwards, the concat method is available to us.
    var array1 = [1, 2, 3, 4, 5];
    var array2 = [6, 7, 8, 9, 10];
    var array3 = array1.concat(array2);
    
    console.log(array3); // [1,2,3,4,5,6,7,8,9,10]

    Chaining is also available for concat.

    var array4 = [1, 2, 3, 4];
    var array5 = [5, 6, 7];
    var array6 = [8, 9, 10];
    var array7 = array4.concat(array5).concat(array6);
    
    console.log(array7); // [1,2,3,4,5,6,7,8,9,10]

     

  2. ES6 introduced the spread operator (…) for merging purposes.
    let array1 = [1, 2, 3, 4, 5]
    let array2 = [6, 7, 8, 9, 10];
    let array3 = [...array1, ...array2];
    
    console.log(array3); // [1,2,3,4,5,6,7,8,9,10]

    And there is no need for chaining, because you can use the spread operator again and again.

    let array4 = [1, 2, 3, 4];
    let array5 = [5, 6, 7];
    let array6 = [8, 9, 10];
    let array7 = [...array4, ...array5, ...array6];
    
    console.log(array7); // [1,2,3,4,5,6,7,8,9,10]

     

  3. The same results can obviously be accomplished in multiple ways. Another way is by using the reduce, or reduceRight functions on an array. The reason why this works really well is because reduce has a parameter for setting the default value. It’s not really the best approach for chaining multiple merges, but for merging two collections, it’s quite powerful. Let’s see how it works.
    let array8 = [100, 200, 300, 400, 500];
    let array9 = [600, 700, 800, 900, 1000];
    array8 = array9.reduce(function(collection, item) {
        collection.push(item);
        return collection;
    }, array8);
    
    console.log(array8); // [100,200,300,400,500,600,700,800,900,1000]

    Here we set array8 to itself (default value parameter) and then iterate over array9 to push all of array9’s items onto array8.

If you know alternative ways to merge arrays please leave a comment.

 

 

LEAVE A REPLY

you might also like