Tag Archives: sort

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]) {
            ret.push(arr[i]);
        }
    }
    return ret;
}
console.log(sort_unique(['237','124','255','124','366','255']));
//["124", "237", "255", "366"]

Nifty.

MySQL: How to Perform an Order By Sort before a Group By Action CodeUnit 25 JUN 2012

Running an order by sort on a result set before applying the group by call – It’s a pretty common problem and an unfortunate result of the way in which MySQL has chosen to implement the SQL language specification.

At the heart of it all, MySQL performs any group by operation before an order by operation, meaning that you usually won’t get quite what you’re after – for example, if you are trying to get the last received feedback for every client in your database, you’ll quickly find that you fall short if you don’t fall back on this most basic of solutions to the order by before group by dilemma: running a subquery.

A subquery is a SELECT statement within another statement, and although you take a very minor performance hit, it does solve the problem very elegantly.

Essentially what you want to do is run your original statement with the order by applied, and then on this resulting statement (technically a temporary table), you then want to run the group by operation.

And luckily for us, it is as easy to implement as what it is to understand. In practice:

SELECT * FROM (SELECT * FROM `clientfeedback` ORDER BY `timestampcaptured` DESC) GROUP BY `clientname`

Nifty.

PHP: How to Sort Your Array but Keep Your Keys CodeUnit 06 APR 2010

PHP comes bundled with a range of nifty array sorting functions the simplest of which will simply take your array and sort it either alphabetically or numerically, acting on the array object itself rather than creating a new, sorted object.

But if you have an associative array, in other words an array with keys, running the sort() function might give you a little shock once it has finished executing – if you check out your array, you’ll notice all of your precious array keys have been completely wiped out, obviously not the greatest of lessons to be learned.

In order to get around this, PHP gives us the asort() function which sorts the values contained in an array accordingly, but at the same time retains all of the original value keys. Similarly, the arsort() function sorts the array in the reverse direction, once again saving the original keys.

(If however you wish to sort on the keys of an array, you can look towards ksort() which literally sorts an array according to its keys and not the values it contains!)

You’ll note that while all these sort functions accept a first parameter which is the actual array to sort, they also come with a secondary, optional parameter which allows you to set just how the array is to be sorted. The following sorting options are available to you:

...