The array.sort() method is a built-in JavaScript method utilized to sort the elements of an array in place and returns the sorted array. The sorting is not numerical but lexicographical, that means it sorts numbers as strings.
Let's take a quick example on how you can use the array.sort() method:
let array = [3, 1, 4, 1, 5, 9];
array.sort();
console.log(array);
// Output: [1, 1, 3, 4, 5, 9]
In this example, the method array.sort()
is called on the array. The sorted array is then logged to the console.
When working with arrays of strings, the array.sort()
method sorts elements as strings in lexicographic (or "dictionary") order:
let array = ['cat', 'Dog', 'bird', 'elephant'];
array.sort();
console.log(array);
// Output: ["Dog", "bird", "cat", "elephant"]
Note that the sort is case-sensitive resulting in a sorted array with capital letter 'D' from 'Dog' appearing before lower case 'b' from 'bird'.
To sort numbers in an ascending order, you need to pass a comparison function to the array.sort()
method:
let array = [40, 1, 10, 200, 21];
array.sort(function(a, b){return a - b});
console.log(array);
// Output: [1, 10, 21, 40, 200]
In this instance, the comparison function is used to correctly sort the numbers in ascending order.
While array.sort()
is a powerful tool, there are a few best practices to keep in mind:
In conclusion, the JavaScript array.sort()
method is a versatile tool to sort both number and string arrays, when used correctly and with an understanding of its lexicographic sorting rules.