How to use Array sort() method in JavaScript


If we want to sort an array using JavaScript easiest way is using sort() method in JavaScript.
By default sort() method get values as strings and sort them in alphabetical and ascending order.
This is how we use this method in JavaScript.

Using sort() method.

var names=['Jack','Eve','Ann','Jane']; 
names.sort(); 

var numbers=[22,56,3,10,6]; 
numbers.sort();

After using sort() method your result arrays will be like,

['Ann','Eve','Jack','Jane']
[10,22,3,56,6]

you will notice that integer array was not sorted correctly. That is because sort() method get values as strings and when comparing 22 is smaller than 3 because 2(first character of 22) is smaller than 3.

Using overloaded method.

To over come this problem there is overloaded method of sort() that take a compare function as a parameter.

var numbers=[22,56,3,10,6];
numbers.sort(function(a,b){return a-b}); 

After using this method your numbers array will be sorted correctly in ascending order as,
[ 3, 6, 10, 22, 56]

As compare function is used to compare integers when comparing 3 and 22,
compare function will be used as function(3,22) and return value 3-22 = -19. 3 will be identified as smaller than 22 because compare function returned a minus value.

If function(a,b){return a-b} is used as compare function integer array will be sorted in descending order.
feel free to comment below if you have any questions or something to add.


No comments:

Post a Comment