Array merge in JavaScript

What makes array to merge in JavaScript?

Actually there aren’t so many array functions in JavaScript. As you know you can join, sort, etc. which methods are pretty basic. What I’d like to do is something similar to PHPs’ array_merge and than array_unique.

With JavaScript that seems pretty impossible. You can merge them with the .concat function as in the example bellow:

var a = [1,2];
var b = [3,4];
a.concat(b);

this gives you array with four elements. But when it comes to trim all the duplicates as it’s array_unique in PHP, well that’s really impossible. You’ve to do it by yourself, and I don’t thing this is the best technique. That slows down the code and you should avoid it!

2 thoughts on “Array merge in JavaScript

  1. James Heo’s solution is not exacty the .concat() is doing. .concat() it’s more of using Array.prototype.push() with loop from b[0] to b[b.length-1] instead.

    The reason James Heo’s short hand version seems to be logical and short, but it involved array a and array b cast to a string first. Then apply string method to split again back to array.

    the .push() method will be quicker because it doesn’t have to go through array a again. It starts to push element one by one depend on the array b’s total length instead.

    Also.. both.. does not help for uniqueness. If you are going to deal with conversion first, converts into hash which will automatically give you the uniqueness.

    function concate(a, b) {
    var obj = {}, result = [];

    for(var i=0;i<b.length;i++) {
    a.push(b[i]); // merge b into a. This is = a.concate(b);
    }

    for(var i=0;i<a.length;i++) {
    obj[a[i]] = a[i]; // find uniqueness
    }

    for (prop in obj) { // converts obj to array
    if (hasOwnProperty.call(obj, prop)) {
    result.push(obj[prop]);
    }
    }

    return result;
    }

    var a = [34, 203, 3, 746, 200, 984, 198, 764, 9];
    var b = [1,3,5,7,8,9,203,200];

    console.log(concate(a,b));

Leave a Reply

Your email address will not be published. Required fields are marked *