sort() Method
The sort()
method sorts the elements of an array, but unlike other iterating methods, it sorts the original array.
- Sorts and modifies the original array.
- Returns the modified array, that is, a reference to the sorted original array.
- Sorts in ascending order by default.
- Sorts by converting the values to a string and comparing their ordinal numbers in the Unicode table.
Such an array of numbers will be sorted in ascending order.
const scores = [61, 19, 74, 35, 92, 56];
scores.sort();
console.log(scores); // [19, 35, 56, 61, 74, 92]
However, since by default the values are converted to a string, the standard sorting of numbers works in an unusual way. Therefore, in the next exercise, let’s look at how to set a custom sort order.
const scores = [27, 2, 41, 4, 7, 3, 75];
scores.sort();
console.log(scores); // [2, 27, 3, 4, 41, 7, 75]
The array of strings is sorted alphabetically.
const students = ["Vika", "Andrey", "Oleg", "Julia", "Boris", "Katya"];
students.sort();
console.log(students); // ['Andrey', 'Boris', 'Julia', 'Katya', 'Oleg', 'Vika'];
The ordinal number of uppercase letters is less than that of lowercase letters.
const letters = ["b", "B", "a", "A", "c", "C"];
letters.sort();
console.log(letters); // ['A', 'B', 'C', 'a', 'b', 'c']
Because the original array is sorted, the purity of functions is violated, and you cannot conveniently make several derived collections based on the original one--to make a collection sorted in ascending order and another in descending order, for example. Therefore, before sorting, make a full copy of the original array and then sort it.
const scores = [61, 19, 74, 35, 92, 56];
const ascendingScores = [...scores].sort();
console.log(scores); // [61, 19, 74, 35, 92, 56]
console.log(ascendingScores); // [19, 35, 56, 61, 74, 92]
Custom sort order for numbers
To set your sort order, you need to pass a callback with two parameters to the sort(compareFunction)
method. This is a compare function, and the sort order depends on its result. The sort()
method will call it on two arbitrary elements.
array.sort((a, b) => {
// Callback body
});
a
is the first element to compare.b
is the second element to compare.
If calling compareFunction(a, b)
returns any negative value, that is, a
is less than b
, after sorting a
will be before b
. This is sorting in ascending order.
const scores = [61, 19, 74, 35, 92, 56];
const ascendingScores = [...scores].sort((a, b) => a - b);
console.log(ascendingScores); // [19, 35, 56, 61, 74, 92]
If calling compareFunction(a, b)
returns any positive value greater than zero, that is, b
is greater than a
, after sorting b
will be before a
. This is sorting in descending order.
const scores = [61, 19, 74, 35, 92, 56];
const descendingScores = [...scores].sort((a, b) => b - a);
console.log(descendingScores); // [92, 74, 61, 56, 35, 19]
If calling compareFunction(a, b)
returns 0, sorting will leave a
and b
unchanged relative to each other, but sort them in relation to all other elements. However, it does not really matter what is returned if their mutual position is of no importance.
Custom sort order for strings
To sort strings alphabetically, in ascending or descending order, use the localeCompare()
string method.
firstString.localeCompare(secondString)
It is invoked on the string to be compared (firstString
) with the one passed as an argument (secondString).
"a".localeCompare("b"); // -1
"b".localeCompare("a"); // 1
"a".localeCompare("a"); // 0
"b".localeCompare("b"); // 0
- Returns a negative value if
firstString
must come beforesecondString
. - Returns a positive value greater than zero if
firstString
must come aftersecondString
. - If the strings are equal, zero is returned.
This is useful when sorting strings, since the sort()
method expects the same values from the callback.
const students = ["Vika", "Andrey", "Oleg", "Julia", "Boris", "Katya"];
const inAlphabetOrder = [...students].sort((a, b) => a.localeCompare(b));
console.log(inAlphabetOrder); // ['Andrey', 'Boris', 'Julia', 'Katya', 'Oleg', 'Vika']
const inReversedOrder = [...students].sort((a, b) => b.localeCompare(a));
console.log (inReversedOrder); // ['Vika', 'Oleg', 'Katya', 'Julia', 'Boris', 'Andrey']
Sorting objects
When working with an array of objects, sorting is done by the numeric or string value of a property. For example, there is a group of students with test scores. You need to sort the array of objects in ascending and descending orders by scores, and by student names.
const students = [
{ name: "Mango", score: 83 },
{ name: "Poly", score: 59 },
{ name: "Ajax", score: 37 },
{ name: "Kiwi", score: 94 },
];
const inAscendingScoreOrder = students.sort(
(firstStudent, secondStudent) => firstStudent.score - secondStudent.score
);
const inDescendingScoreOrder = students.sort(
(firstStudent, secondStudent) => secondStudent.score - firstStudent.score
);
const inAlphabeticalOrder = students.sort((firstStudent, secondStudent) =>
firstStudent.name.localeCompare(secondStudent.name)
);