Search code examples
javascriptjqueryarraysunique

Remove similar elements in array of numbers


I have an array of numbers, like: [1, 4, 7, 1, 2, 1, 3, 1, 4].

I would like to remove duplicate elements and sort the result, i.e. the required result is:
[1, 2, 3, 4, 7].

Is there any built in Javascript/jQuery functions to do this, or I must write my own ?


Solution

  • No, there's nothing built-in. Also, you need to be aware that the default sort is lexical, so [9, 1, 10].sort() will return [1, 10, 9].

    The following will sort and remove duplicates from an array of numbers in place:

    function sortAndRemoveDuplicates(arr) {
        arr.sort( function(a, b) { return a - b; } );
        var copy = arr.slice(0);
        arr.length = 0;
    
        for (var i = 0, len = copy.length; i < len; ++i) {
            if (i == 0 || copy[i] != copy[i - 1]) {
                arr.push(copy[i]);
            }
        }
        return arr;
    }
    
    var arr = [1, 4, 7, 1, 2, 1, 3, 10, 1, 4, 10];
    sortAndRemoveDuplicates(arr);
    console.log(arr); // [1, 2, 3, 4, 7, 10]