Lecture

Array Method - Sort

The sort() method sorts the elements of an array in place and returns the sorted array.

By default, the sorting order is ascending for numbers and according to Unicode sorting order for strings.

You can change the sorting order by providing a compareFunction that defines the sort order.


Sorting an Array of Strings

Alphabetical String Sorting
const fruits = ['cherry', 'apple', 'banana']; fruits.sort(); console.log(fruits); // ['apple', 'banana', 'cherry']

Here, 'cherry', 'apple', 'banana' are sorted alphabetically based on their Unicode positions.


Sorting an Array of Numbers

By default, sort converts numbers into strings and then sorts them.

Numbers Sorted as Strings
const numbers = [10, 2, 33, 14]; numbers.sort(); console.log(numbers); // [10, 14, 2, 33]

When 10, 2, 33, 14 are converted to strings and sorted, strings that start with the character '1' appear first, which is why the array does not sort as expected to [2, 10, 14, 33].

To sort an array of numbers in ascending order, you need to specify a sorting criteria using compareFunction.

The compareFunction is used as arr.sort(compareFunction), and it defines a criteria for sorting the array elements.

This function accepts two arguments, and if it returns a value less than 0, the first argument is sorted before the second argument.

If it returns 0, their order is unchanged. If it returns a value greater than 0, the second argument is sorted before the first.


Ascending Order Sorting of Numbers
const numbers = [10, 2, 33, 14]; // compareFunction: (a, b) => a - b numbers.sort((a, b) => a - b); // Ascending order sort console.log(numbers); // [2, 10, 14, 33]

Here, the compareFunction is (a, b) => a - b.

The function first compares 10 and 2. Since 10 - 2 is 8 (greater than 0), 2 is sorted before 10.

Next, 10 is compared to 33. Since 10 - 33 is -23 (less than 0), 10 is sorted before 33.

Following these comparisons, the numbers array is sorted to [2, 10, 14, 33].


Sorting Objects in an Array

In JavaScript, objects don't have a natural order. To sort objects in an array based on a specific key, use compareFunction as shown below.

Sorting Students by Height
const students = [ { name: 'John', height: 170 }, { name: 'Alice', height: 160 }, { name: 'Michael', height: 175 }, ]; // Sort students by height in ascending order students.sort((a, b) => a.height - b.height); console.log(students);

Here, students are sorted by their height property in ascending order.

Mission
0 / 1

What is the most appropriate answer to fill in the blank?

To sort an array of numbers in ascending order, you need to pass a compareFunction to the method.
sort()
push()
pop()
map()

Lecture

AI Tutor

Design

Upload

Notes

Favorites

Help

Code Editor

Run

Execution Result