DEV Community

Cover image for .sort() Method | JavaScript
Akyu0002 (Tibet)
Akyu0002 (Tibet)

Posted on • Updated on

.sort() Method | JavaScript

Array.prototype.sort()

Simply put, .sort(), sorts elements of an array, by default it sorts values in alphabetical and ascending order.

We can use this without any parameters for simple string and number sorting.

Remember: .sort() method mutates the original array!

String Example:

const profs = ['Robert', 'Tony', 'Vladamir', 'Adam', 'Steve'];
profs.sort();
console.log(profs);

Output: [ 'Adam', 'Robert', 'Steve', 'Tony', 'Vladamir' ]
Enter fullscreen mode Exit fullscreen mode

Number Example:

const numbers = [20, 33, 54, 100, 205];
numbers.sort();
console.log(numbers);

Output: [ 100, 20, 205, 33, 54 ]
Enter fullscreen mode Exit fullscreen mode

There is a flaw in the sort method, why did 100 come before the rest of these numbers?

The method is converting the elements to strings and comparing them in UTF-16 code units.

That is why "100" is being put at the front of the array, and the same goes for "205" being in the middle of the array.

To fix this error in sorting, we can use the compare function.

function(a, b){
return a - b
}
Enter fullscreen mode Exit fullscreen mode

When the .sort() method is comparing our two values (a, b), it sorts the values in accordance to whats returned.

It will return either a negative, a positive or a zero.

  • If it returns a value < than 0 then a is sorted before b

  • If it returns a value > than 0, then b is sorted before a

  • If it returns a value = 0, the sort order does not change.

Compare Function Example:

const numbers = [20, 33, 54, 100, 205]
numbers.sort(function(a, b) {
  return a - b
});
console.log(numbers)

Output: [ 20, 33, 54, 100, 205 ]
Enter fullscreen mode Exit fullscreen mode

In ES6, we can also do this using an arrow function expression.

let numbers = [20, 33, 54, 100, 205]
numbers.sort((a, b) => a - b);
console.log(numbers);

Output: [ 20, 33, 54, 100, 205 ]
Enter fullscreen mode Exit fullscreen mode

Reversing a Sorted List

If we ever need to reverse out sorted array all we need to do is switch a - b to b - a!

let numbers = [20, 33, 54, 100, 205]
numbers.sort((a, b) => a-b);
console.log(numbers);

Output: [ 205, 100, 54, 33, 20 ]
Enter fullscreen mode Exit fullscreen mode

Reverse using .reverse()
Although this method is not recommended because it could lead to unexpected results, it is an easy way to reverse your list.

let numbers = [20, 33, 54, 100, 205]
numbers.sort((a, b) => a - b).reverse();
console.log(numbers);

Output: [ 205, 100, 54, 33, 20 ]
Enter fullscreen mode Exit fullscreen mode

In Conclusion

There are many ways of working with the .sort() method, but these basics should help you get a good understanding of how the method works.

To learn about more complex uses of this method, check out this fantastic video!

STEEEEEVEEE

Top comments (1)

Collapse
 
idrysas profile image
Idrysas

thanks you