Skip to content
Advertisement

Merging of two arrays, store unique elements, and sorting in jQuery

var Arr1 = [1,3,4,5,6];

var Arr2 = [4,5,6,8,9,10];

I am trying to do merge these two arrays and output coming is [1,3,4,5,6,4,5,6]

I have used $.merge(Arr1, Arr2); this piece to merge them. Using alert I can see the merged array like above.

Now my question is how can I get the following output: [1,3,4,5,6,8,9,10]

i.e. the elements should be unique as well as sorted in the same manner I have mentioned.

Please help.

Advertisement

Answer

You can use Array.prototype.sort() to do a real numeric sort and use Array.prototype.filter() to only return the unique elements.

You can wrap it into a helper similar to this:

var concatArraysUniqueWithSort = function (thisArray, otherArray) {
    var newArray = thisArray.concat(otherArray).sort(function (a, b) {
        return a > b ? 1 : a < b ? -1 : 0;
    });

    return newArray.filter(function (item, index) {
        return newArray.indexOf(item) === index;
    });
};

Note that the custom sort function works with numeric elements only, so if you want to use it for strings or mix strings with numbers you have to update it off course to take those scenarios into account, though the rest should not change much.

Use it like this:

var arr1 = [1, 3, 4, 5, 6];
var arr2 = [4, 5, 6, 8, 9, 10];

var arrAll = concatArraysUniqueWithSort(arr1, arr2);

arrAll will now be [1, 3, 4, 5, 6, 8, 9, 10]


DEMO – concatenate 2 arrays, sort and remove duplicates


There is many ways of doing this I’m sure. This was just the most concise I could think off.

Advertisement