The Sort Method
Part of the Logic & Flow section of Coddy's JavaScript journey — lesson 57 of 65.
The sort() method allows you to sort the elements of an array in place and returns the sorted array. By default, it sorts elements as strings in alphabetical and ascending order.
Here is the basic syntax:
array.sort([compareFunction])Example without using the compare function:
const fruits = ['banana', 'apple', 'orange', 'mango'];
fruits.sort();
console.log(fruits);
// ['apple', 'banana', 'mango', 'orange']WARNING: Numbers don't sort as expected without compare function:
const numbers = [1, 30, 4, 21, 100000];
numbers.sort();
console.log(numbers);
// [1, 100000, 21, 30, 4] (incorrect numeric sorting)To sort numbers correctly or implement custom sorting, you need to use a compare function.
The compare function should return:
- A negative value if a should come before b
- A positive value if b should come before a
- Zero if they are equal
Here's how you would sort numbers using a compare function:
// Ascending order
const numbers = [1, 30, 4, 21, 100000];
numbers.sort((a, b) => a - b);
console.log(numbers); // [1, 4, 21, 30, 100000]// Descending order
numbers.sort((a, b) => b - a);
console.log(numbers); // [100000, 30, 21, 4, 1]Another example of how to sort objects:
const people = [
{ name: 'John', age: 30 },
{ name: 'Alice', age: 25 },
{ name: 'Bob', age: 35 }
];
// Sort by age (ascending)
people.sort((a, b) => a.age - b.age);// Sort by name (alphabetically use localeCompare())
people.sort((a, b) => a.name.localeCompare(b.name));Challenge
EasyCreate a function named sortByLength that takes an array of strings and returns a new array with the same strings sorted by their length in ascending order. If two strings have the same length, they should be sorted alphabetically.
Cheat sheet
The sort() method sorts array elements in place and returns the sorted array. By default, it sorts elements as strings in alphabetical order.
Basic syntax:
array.sort([compareFunction])Sorting strings:
const fruits = ['banana', 'apple', 'orange', 'mango'];
fruits.sort();
console.log(fruits); // ['apple', 'banana', 'mango', 'orange']Warning: Numbers don't sort correctly without a compare function:
const numbers = [1, 30, 4, 21, 100000];
numbers.sort();
console.log(numbers); // [1, 100000, 21, 30, 4] (incorrect)Compare function returns:
- Negative value if a should come before b
- Positive value if b should come before a
- Zero if they are equal
Sorting numbers correctly:
// Ascending order
numbers.sort((a, b) => a - b);
// Descending order
numbers.sort((a, b) => b - a);Sorting objects:
const people = [
{ name: 'John', age: 30 },
{ name: 'Alice', age: 25 },
{ name: 'Bob', age: 35 }
];
// Sort by age
people.sort((a, b) => a.age - b.age);
// Sort by name alphabetically
people.sort((a, b) => a.name.localeCompare(b.name));Try it yourself
function sortByLength(arr) {
return arr.sort((a, b) => {
// Write code here
})
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
1Strings In Depth
String FundamentalsIterate Over StringsTemplate LiteralsString MethodsRecap - String Weaver4JSON Part 2
Iterate Over JSONNested JSONJSON Optional ChainingShallow And Deep CopyRecap - Bicycle ShopRecap - Solar System10Manage Festival System
Project OverviewAdd Movies & Venues2Multi-dimensional Arrays
2D Arrays BasicsAccessing 2D Array ElementsNested Loops with 2D ArraysRecap - 2D ArraysMatrix Addition & SubstractionJagged Arrays3D Arrays And BeyondCommon 2D Array PatternsRecap - All About Arrays5Sets Part 1
What Is A Set?Iterating Over SetsAdding An ElementRemoving An ElementChecking If An Element ExistsSize And Is EmptyCopy And ClearRecap - Basic Of Sets8Arrays Interesting Topics
Array DestructuringSpread Syntax in ArraysSparse ArraysRecap - Arrays Workshop3JSON Part 1
What is a JSON?Check If Key ExistsObject MethodsThe Spread Operator Part 1The Spread Operator Part 2Remove KeysRecap - JSON Manipulate Keys