Array Method - Sort
The sort()
method sorts the elements of an array in place and returns the sorted array.
The default sort order is ascending by converting the elements into strings and comparing their sequences of UTF-16 code unit values.
You can provide a compareFunction
to define the sort order.
Sorting an Array of Strings
const fruits = ['Cherry', 'Backpack', 'Tree'];
fruits.sort();
console.log(fruits); // ['Backpack', 'Cherry', 'Tree']
Here, 'Cherry', 'Backpack', and 'Tree' are sorted alphabetically based on their UTF-16 code unit values.
Sorting an Array of Numbers
By default, sort converts numbers to strings and sorts them.
const numbers = [10, 2, 33, 14];
numbers.sort();
console.log(numbers); // [10, 14, 2, 33]
The numbers 10, 2, 33, and 14 are sorted as strings, so the number series is not in the expected order [2, 10, 14, 33].
To sort an array of numbers in ascending order, you need to define a compareFunction
that specifies the sort order.
A compareFunction
is used as arr.sort(compareFunction)
where the function defines the sorting order.
The function takes two arguments, and returns a value that is less than zero if the first argument is less than the second, zero if they are equal, and greater than zero if the first argument is greater than the second.
const numbers = [10, 2, 33, 14];
// compareFunction: (a, b) => a - b
numbers.sort((a, b) => a - b); // Ascending order
console.log(numbers); // [2, 10, 14, 33]
In this example, the compareFunction
is (a, b) => a - b
.
The function compares 10 and 2 first. Since 10 - 2 is 8 (greater than zero), 2 comes before 10.
Next, it compares 10 and 33. Since 10 - 33 is -23 (less than zero), 10 comes before 33.
This process continues for all elements, resulting in the array [2, 10, 14, 33]
.
Example 3: Sorting Objects in an Array
In JavaScript, objects do not have a defined order. To sort an array of objects by a specific property, you need to use a compareFunction
.
const students = [
{ name: 'John', height: 170 },
{ name: 'Alice', height: 160 },
{ name: 'Mike', height: 175 },
];
// Sort students by height in ascending order
students.sort((a, b) => a.height - b.height);
console.log(students);
In this example, the students are sorted by their height in ascending order.
Want to learn more?
Join CodeFriends Plus membership or enroll in a course to start your journey.