Possible Duplicate:
Javascript array sort and unique
I was surprised to see that there is no built in jQuery function for that.
I’ve seen many solutions on stackoverflow, but the questions were polluted with not-working answers (to find a working one I had to test them all).
So, for future reference and to spare other users the trouble I decided to post this Q&A style.
How to return unique and sorted array values useing jQuery?
Numbers:
// input array
var inputArray = [10, 5, 15, 10, 5, 15];
// expected result array
var resultArray = [5, 10, 15];
Strings:
// input array
var inputArray = ['b', 'a', 'c', 'b', 'a', 'c'];
// expected result array
var resultArray = ['a', 'b', 'c'];
I will take upon myself to add my answer here, instead of the previously asked question simply because the answer in the previously asked question is bad, but I don’t hope for the author to alter the decision.
Now, to give you some more intuition into the solution that I propose: Sorting is O(n log n), removing duplicates is O(n), so we conclude that the entire operation should be no more complex then n log n. However, if you think of it, n will never increase, but will most likely decrease if you first remove duplicates, and then sort. So, while on the surface of it, it is still O(n log n), it will be generally faster. You could probably improve it (in other languages) by collecting values into a tree instead of a hash-table, but given the tremendous difference in performance between the “native” data structures and custom ones in JavaScript – the solution below should be optimal: