September 30, 2018 · Javascript

How to use Array.sort()

Array.prototype.sort() is used to order elements of an array in specific order.

if used as is, the sorting occurs converting elements to strings and using  the Unicode value of the first letter of the string

Example

let arr = [1,3,2,4,6,11,3,6,8,7,9,5,10];
arr.sort();
console.log(arr);
// (12) [1, 10, 11, 2, 3, 3, 4, 5, 6, 6, 7, 8, 9]

The Unicode Character 10 comes before 2, so the result is what we see in the example.

Since number 10 or 11 does not appear on the Unicode list, the algorithm takes the first number it sees on the array to process the sorting.

The same happens when sorting words, the algorithm take the first letter to sort the array, let's see an example.

let arr = ["house", "papaya", "GrandFleet", "Housing"];
arr.sort();
console.log(arr);
// ["GrandFleet", "Housing", "house", "papaya"];

Capital letters come before lowercase letters in Unicode list, so the algorithm sort GrandFleet and Housing before house and papaya in the array, the next factor to take into account is the order of the letters in the alphabet.

However, what if we want to specify the condition by which to sort the array.

then we should pass a [compareFunction] parameter to the sort function
Syntax
arr.sort([compareFunction])

For example, lets sort from lowest to highest.

let arr = [1,3,2,4,6,11,3,6,8,7,9,5,10];
arr.sort((a, b) => {
     return a - b;
});
// (13) [1, 2, 3, 3, 4, 5, 6, 6, 7, 8, 9, 10, 11]

The compare function takes control of the sorting mechanism, and the result is an array sorted from lowest to highest.

If you want to go deeper on sorting algorithms explained, check my post on sorting algorithms explained

bibliographyhttps://en.wikipedia.org/wiki/Sorting_algorithmhttps://unicode-table.com/es/#control-characterhttps://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort

  • LinkedIn
  • Tumblr
  • Reddit
  • Google+
  • Pinterest
  • Pocket