JavaScript arrays can be somewhat intimidating. They tend to not have all the available functions/methods that other languages like PHP and Ruby have for manipulating arrays.
Making a JS array unique isn’t a simple one-liner. This short article is for developers trying to make a JavaScript array unique without leaving holes in your array. Sorting an array in JavaScript is simple in most cases. Just call the sort() method on the array like so.
var my_array = [5, 2, 4, 6, 9]; my_array.sort();
One caveat to be aware of with this method of sorting is that it performs a non-lexicographical sort, which might be confusing for human users if you display it on screen. Depending on your requirements, you might want to change your sorting algorithm. Check out Brian Huisman’s article on the subject.
After sorting the array, the following snippet will remove any duplicate entries
for ( var i = 1; i < my_array.length; i++ ) {
if ( my_array[i] === my_array[ i - 1 ] ) {
my_array.splice( i--, 1 );
}
}
This will iterate over each element in the array, attempting to find elements where the value is equal to the previous value. If they are equal, we have found a duplicate so we remove it using splice.
A complete function for sorting and making an array unique in JavaScript would look like the following
function sort_and_unique( my_array ) {
my_array.sort();
for ( var i = 1; i < my_array.length; i++ ) {
if ( my_array[i] === my_array[ i - 1 ] ) {
my_array.splice( i--, 1 );
}
}
return my_array;
};


