JavaScript

JavaScript Sort Array Example

Array sorting is a key development technique applied in a variety of situations. Below we’ll show you exactly how to use Sort Array, be it sorting an array of numbers, names or structures, ascending, descending or even randomizing and reversing an array.

The sort() method

The sort() method sorts the elements of an array and returns the array. The sort is not necessary stable (read here for more information). The syntax for the function is like this:

arr.sort([compareFunction])

The sort() function takes the optional parameter compareFunction. This parameter specifies the sort order, and if omitted the sorting will go according to string Unicode code points. What if it’s not omitted?

In this case the array elements are sorted according to the return value of the compareFunction. Which means, if a and b were two elements being compared then when the return value is less than 0, a is sorted to a lower index than b, if the return value is 0 than they’re equal, and if the return value is greater than 0, a is sorted to a higher index than b. Beware that compareFunction(a, b) must always return the same value when given a specific pair of elements as it’s arguments. If inconsistent results are returned then the sort order is undefined.

Sorting strings

So let’s get to actually using them. The easiest use of the sort() function is sorting an array of strings. The code will go like this:

var stringArray = ['Blue', 'Humpback', 'Beluga'];

console.log('stringArray:', stringArray.join());
console.log('Sorted:', stringArray.sort());

We have only declared the array, and printed it as it was originally, and also after sorting. Pretty simple so far.

Sorting Numbers

Now let’s compare numbers:

var numberArray = [40, 1, 5, 200];

function compareNumbers(a, b) {
    return a - b;
}

console.log('numberArray:', numberArray.join());
console.log('Sorted without a compare function:', numberArray.sort());
console.log('Sorted with compareNumbers:', numberArray.sort(compareNumbers));

The output will look like this:

numberArray: 40,1,5,200
Sorted without a compare function: 1,200,40,5
Sorted with compareNumbers: 1,5,40,200

You’ve certainly noticed that in using sorting without the compareNumbers function, the sorting is not correct, as 200 is very much greater than 5. This happens because as we told you in the beginning, the default way of sorting is by considering numbers as strings and comparing them based on Unicode code points.

Sorting numeric strings

We saw what happens when we compare strings, and what happens when we compare numbers. What we didn’t mention is what happens when we compare numeric string. This is the code:

var numericStringArray = ['80', '9', '700'];

console.log('numericStringArray:', numericStringArray.join());
console.log('Sorted without a compare function:', numericStringArray.sort());
console.log('Sorted with compareNumbers:', numericStringArray.sort(compareNumbers));

And this is how the output will look like:

numericStringArray: 80,9,700
Sorted without a compare function: 700,80,9
Sorted with compareNumbers: 9,80,700

So now you see that the numeric strings sorted without a compare function are sorted according to Unicode code points, but with a compare function they are treated entirely like numbers.

Mixed numeric Arrays

The other combination of numbers and strings we haven’t mentioned is a mixed array of numbers of strings. The code will go like this:

var mixedNumericArray = ['80', '9', '700', 40, 1, 5, 200];

console.log('mixedNumericArray:', mixedNumericArray.join());
console.log('Sorted without a compare function:', mixedNumericArray.sort());
console.log('Sorted with compareNumbers:', mixedNumericArray.sort(compareNumbers));

You might have guessed what the output will look like. Anyway, you can see it below, just to check:

mixedNumericArray: 80,9,700,40,1,5,200
Sorted without a compare function: 1,200,40,5,700,80,9
Sorted with compareNumbers: 1,5,9,40,80,200,700

Sorting non-ASCII characters

By now you now how to sort numbers and strings and whatnot, but if you live in a country which uses special characters (my country uses “ç” and “ë”) you might be thinking: How do I sort strings that contain those characters?

It’s very easy: you use the function localeCompare like this:

var items = ['réservé', 'premier', 'cliché', 'communiqué', 'café', 'adieu'];
items.sort(function (a, b) {
  return a.localeCompare(b);
});

It will turn out this array:

adieu, café, cliché, communiqué, premier, réservé

As easy as pie.

Sorting Maps

Sometimes you will have array elements, so different from each other that you will have no option but to use the compareFunction multiple times. As the number of elements, and the complexity of the compareFunction increases, the need for using sorting maps increases too. The general idea of sorting maps is to walk the array once and extract the actual values used for sorting in a temporary array, and then sort the temporary array to get the sorted array. This is the list we’ll sort this time:

var list = ['Delta', 'alpha', 'CHARLIE', 'bravo'];

The temporary holder of position and sort value will look like this:

var map = list.map(function(e, i) {
    return { index: i, value: e.toLowerCase() };
})

The sorting map’s code containing the reduced values will be this:

map.sort(function(a, b) {
    return +(a.value > b.value) || +(a.value === b.value) - 1;
});

And finally, the container for the resulting order is this:

var result = map.map(function(e){
    return list[e.index];
});

So now you can even use sorting maps! But it’s not all. How about some reversing and randomizing arrays?

Reversing Arrays

To reverse array we use the function reverse(), which just puts the first element in last place and so on until the last element is placed first. The following code snippet is the creation and reversing of an array:

var myArray = ['one', 'two', 'three'];
myArray.reverse(); 

console.log(myArray) // ['three', 'two', 'one']

Now on to the next exciting thing: Shuffling.

Randomizing arrays

The most used and unbiased algorithm for shuffling is the Fisher-Yates Shuffle also known as Knuth Shuffle (you can also find it on Github). The code for it will go like this:

function shuffle(array) {
  var currentIndex = array.length, temporaryValue, randomIndex ;

  // While there remain elements to shuffle...
  while (0 !== currentIndex) {

    // Pick a remaining element...
    randomIndex = Math.floor(Math.random() * currentIndex);
    currentIndex -= 1;

    // And swap it with the current element.
    temporaryValue = array[currentIndex];
    array[currentIndex] = array[randomIndex];
    array[randomIndex] = temporaryValue;
  }

  return array;
}

var arr = [2, 11, 37, 42];
shuffle(arr);
console.log(arr);

Let’s explain what we did there. First we set the condition, which is “until the last element of the array”. Then we pick one of the remaining elements, starting from the one we’re at currently, and then we pick a remaining element, after which we reduce the current index by 1. Then we swap that with the current element. The function returns the array.

In the last part of the code we have the actual usage of the function, by giving values to the array.

And that folks, is how we randomize an array.

Download the source code

This was an example of array sorting, using JavaScript.

Download
You can download the source code for this example here: SortArray

Era Balliu

Era is a Telecommunications Engineering student, with a great passion for new technologies. Up until now she has been coding with HTML/CSS, Bootstrap and other front-end coding languages and frameworks, and her recent love is Angular JS.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button