Understanding the Sort Method of Arrays

How to use JavaScript’s sort

Photo by Jozsef Hocza on Unsplash
  • The JavaScript array sort() is used to sort array elements.
  • By default, the array will sort in ascending order, but we can change it.
  • This method will change the original array.
  • We can also provide our comparing function to implement custom sorting.
var array = [1,2,3,1,2,3];
array.sort(); [1,1,2,2,3,3]

Let’s try another example:

var array = [1,2,11];
array.sort(); // [1,11,2]

For the above code, the expected result is [1,2,11], but we get [1,11,2]. The reason is the sort method converts the elements into strings then compares their sequences of UTF-16 code units values.

So the 11 is converted to “11”. When we compare two strings like “11” and “2”, the char code is compared means char code of 1 is 49 , whereas char code of 2 is 50. Because of 49 < 50, we get [1,11,2].

If the array contains any undefined, then all undefined elements are sorted to the end of the array.

We can use the default sort method to sort strings.

var names = ["John", "Abu", "Babu", "Balu", "Antony"]
names.sort();
console.log(names); // ["Abu", "Antony", "Babu", "Balu", "John"]

For other types, we need to pass our compareFunction as an argument to sort Function.

The compare function takes two arguments. The two arguments are taken as from array on index [0,1] , [1,2] … [arrayLength-2, arrayLength-1] for comparing the pair of elements.

The sorting of elements is based on the return value of compareFunction for each pair of comparison.

If the function returns…

  • >0 then the position of a and b is swapped.
  • <=0 then there is no change in position

Let’s write a compare function to sort numbers.

function compare(a, b) {
  if (a < b ) {
return -1;
}
  if (a > b ) {
return 1;
}
  // otherwise a == b
return 0;
}
// Now if we execute

var array = [2,1,11];
array.sort(compare);
log(array); [1,2,11];

The above compare function can be simplified as:

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

Because, when we do a-b, if a > b then it returns number > 0. If a<b, then it returns < 0. When a=b , then it returns 0.

To sort numbers in Descending Order, just change the a-b to b-a .

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

Sorting Array of Objects

var users = [ {name: "John", age:20}, {name:"Antony" , age : 33}];
function sortByAge(obj1, obj2) {
    return obj1.age - obj2.age;
}
function sortByName(obj1, obj2) {
return obj1.name.localeCompare(obj2.name);
}
users.sort(sortByAge);
// output 
0: {name: "John", age: 20}
1: {name: "Antony", age: 33}
users.sort(sortByName);
//output
0: {name: "Antony", age: 33}
1: {name: "John", age: 20}

The localeCompare() method used in sortByName compareFunction returns a number indicating whether a reference string comes before or after or is the same as the given string in sort order.

If the CompareFunction returns undefined, null, NaN, Infinity, then the array will not sort two members

var array = [3,2,1, 110, 102 , 30];
function customCompare(a, b){
if(a > 10 || b > 10) {
return Infinity;
}
else {
return a-b;
}
}
array.sort(customCompare);

In the above example, we have defined if the a and b is less than 10 , it will sort by ascending order. Otherwise, the function will return Infinity, though Infinity > 0. But, it will not be swapped. This is the same for undefined, null, NaN.

View at Medium.com
View at Medium.com

Leave a comment

Design a site like this with WordPress.com
Get started