Sorting Custom Objects
The sort() method sorts array elements in place and returns the sorted array. By default, it sorts elements as strings. To sort numbers or objects, you must provide a compare function.
Compare Function
Section titled “Compare Function”The compare function takes two arguments a and b and returns:
< 0ifashould come beforeb0ifaandbare equal> 0ifashould come afterb
Code Example
Section titled “Code Example”// Sorting numbers correctlyconst numbers = [10, 5, 40, 25];numbers.sort((a, b) => a - b);console.log(numbers); // [5, 10, 25, 40]
// Sorting objects by propertyconst users = [ { name: "Alice", age: 30 }, { name: "Bob", age: 25 }, { name: "Charlie", age: 35 },];
// Sort by age ascendingusers.sort((a, b) => a.age - b.age);console.log(users);// [{ name: "Bob", age: 25 }, { name: "Alice", age: 30 }, { name: "Charlie", age: 35 }]
// Sort by name alphabeticallyusers.sort((a, b) => a.name.localeCompare(b.name));console.log(users);// [{ name: "Alice", ... }, { name: "Bob", ... }, { name: "Charlie", ... }]
// Multi-level sorting: by age, then by nameconst users2 = [ { name: "Alice", age: 30 }, { name: "Bob", age: 25 }, { name: "Charlie", age: 30 },];users2.sort((a, b) => { if (a.age !== b.age) return a.age - b.age; return a.name.localeCompare(b.name);});console.log(users2);// Bob (25), Alice (30), Charlie (30)