The sort()
method in JavaScript works by comparing the elements of an array using a given comparison function, and rearranges the elements in ascending order based on the returned value. If no comparison function is provided, the sort()
method uses the default comparison function, which sorts the elements in ascending order based on their Unicode code points.
In simpler terms before comparison each element of the array is converted into string and compared.
Here is the syntax for the sort()
method:
array.sort([compareFunction])
compareFunction
: An optional comparison function that determines the order of the elements. If this parameter is omitted, the sort()
method will use the default comparison function, which sorts the elements in ascending order based on their Unicode code points.
// Sort an array of strings in descending order
let words = ['cat', 'dog', 'bird', 'ant', 'bee'];
words.sort((a, b) => b.localeCompare(a));
console.log(words); // ['dog', 'cat', 'bee', 'ant', 'bird']
// Sort an array of objects by a property
let cars = [ { make: 'Ford', model: 'Focus' }, { make: 'Toyota', model: 'Corolla' }, { make: 'Honda', model: 'Civic' }];
cars.sort((a, b) => a.make.localeCompare(b.make));
console.log(cars); // [{ make: 'Ford', model: 'Focus' },
{ make: 'Honda', model: 'Civic' },
{ make: 'Toyota', model: 'Corolla' }]
Here is an example of how the sort()
method works with the default comparison function:
let words = ['cat', 'dog', 'bird', 'ant', 'bee'];
words.sort();
console.log(words); // ['ant', 'bee', 'bird', 'cat', 'dog']
In this example, the sort()
method compares the elements of the words
array using the default comparison function, which sorts the elements in ascending order based on their Unicode code points. As a result, the elements are rearranged in the following order: ‘ant’, ‘bee’, ‘bird’, ‘cat’, ‘dog’.
If you want to specify a custom comparison function, you can pass a function as an argument to the sort()
method. The comparison function should take two arguments, a
and b
, and return a negative value if a
should be sorted before b
, a positive value if a
should be sorted after b
, or 0 if a
and b
are equal.
Here is an example of how to use a custom comparison function with the sort()
method:
let numbers = [5, 2, 7, 1, 3, 8, 6, 4];
numbers.sort((a, b) => b - a);
console.log(numbers); // [8, 7, 6, 5, 4, 3, 2, 1]
In this example, the comparison function compares the elements a
and b
and returns the difference between them, which causes the sort()
method to sort the elements in descending order.
let arr = [ 1, 2, 17 ];
// the method reorders the content of arr
arr.sort();
console.log( arr ); // 1, 17, 2
The output of the above code snippet is strange because it converted the elements of the array to string and applied string comparison on it.
You can find the complete JavaScript Tutorials here.
Follow us on Facebook, YouTube, Instagram, and Twitter for more exciting content and the latest updates.