DEV Community

Yong Liang
Yong Liang

Posted on

Javascript Built-in sort() method

How does JS built-in sort() method work?

the sort() method will sort arrays in place and return a sorted array. The default sort order is built upon converting the elements into strings, then comparing their sequences of UTF-16 code units values.

The sort() method accepts a compareFunction(a,b) as argument. In order to sort things propertly, we need to define what the compareFunction does.

Examples

var months = ['March', 'Jan', 'Feb', 'Dec'];
months.sort();
console.log(months);
// expected output: Array ["Dec", "Feb", "Jan", "March"]

var array1 = [1, 30, 4, 21, 100000];
array1.sort();
console.log(array1);
// expected output: Array [1, 100000, 21, 30, 4]

//the results are not sorted correctly.

The default sort() compares elements as strings, so 21 is greater than 10000 because 2 is > 1 for example. In order to fix this we can use the compareFunction.

The compareFunction

These are the rules I found from Mozilla's documentation:

  1. If compareFunction(a, b) is less than 0, sort a to an index lower than b (i.e. a comes first).

  2. If compareFunction(a, b) returns 0, leave a and b unchanged with respect to each other, but sorted with respect to all different elements. Note: the ECMAscript standard does not guarantee this behavior, thus, not all browsers (e.g. Mozilla versions dating back to at least 2003) respect this.

  3. If compareFunction(a, b) is greater than 0, sort b to an index lower than a (i.e. b comes first).

  4. compareFunction(a, b) must always return the same value when given a specific pair of elements a and b as its two arguments. If inconsistent results are returned, then the sort order is undefined.

var numbers = [4, 2, 5, 1, 3];
numbers.sort(function(a, b) {
   return a - b;
 });
 console.log(numbers);

// [1, 2, 3, 4, 5]


//to sort by the length of strings

function lengthCompare(a,b){
    return a.length - b.length 
}

console.log(["grapefruitPlusKiwi", "apple", "pie", "orange", "pineapple", "banananananana"].sort(lengthCompare))

//["pie", "apple", "orange", "pineapple", "banananananana", "grapefruitPlusKiwi"]

source from mozilla

Top comments (0)