Tag Archives: unique

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.

SQL: Add a Unique Compound Key to an Existing MySQL Table CodeUnit 21 JUN 2010

A simple question for today: how does one go about preventing duplicate rows based on the value held by more than one column being inserted into an existing MySQL table?

Well the solution lies in the use of a unique compound key which is basically a way of specifing unique rows based on a value given by a combination of one or more columns.

So for example, if we said we wanted to prevent people sharing the same firstname, surname and title from being added to a persons table, we are in fact specifying a unique compound key to act upon the columns firstname, surname and title!

With this in mind, now adding this key constraint to a table is as simple as running:

ALTER TABLE people ADD UNIQUE KEY (firstname,surname,title)

You’ll note that running this SQL statement on a table containing data already breaking this new rule that we are imposing will fail, meaning that one will first manually have to remove all the offending data before running the ALTER statement again.

And that’s it, a pretty simple little tip for today’s CodeUnit SQL tutorial entry! :)