JavaScript: A Simple Function to Return a Sorted and Unique Array CodeUnit 28 OCT 2012

I came across this useful little JavaScript code snippet which given a simple input array, will both sort it and ensure that it contains unique values.

If you take a look at the code, you’ll notice that the trick is to first sort the array, and once that has been taken care of by JavaScript’s native sort function, we then loop through the array checking that the previous element doesn’t match the element we’re trying to add.

Simple, but works well for very simply arrays which need to be unique in nature (e.g. phone numbers before a batch SMS operation.)

function sort_unique(arr) {
    arr = arr.sort(function (a, b) { return a*1 - b*1; });
    var ret = [arr[0]];
    for (var i = 1; i < arr.length; i++) { // start loop at 1 as element 0 can never be a duplicate
        if (arr[i-1] !== arr[i]) {
    return ret;
//["124", "237", "255", "366"]


Related Posts:

About Craig Lotter

South African software architect and developer at Touchwork. Husband to a cupcake baker and father to two little girls. I don't have time for myself any more.