JavaScript sort() Method
Sort arrays in ascending or descending order with custom comparison logic.
What is sort()?
The sort() method sorts array elements in place and returns the sorted array. By default, it sorts elements as strings in ascending order. Use a comparison function for custom sorting.
Basic sort() Usage
const fruits = ['banana', 'apple', 'cherry'];
fruits.sort();
console.log(fruits); // ['apple', 'banana', 'cherry']
// IMPORTANT: sort() mutates the original array!
console.log(fruits === fruits); // true (same reference)This example demonstrates how the JavaScript sort() method arranges string elements in alphabetical order. It also highlights that sort() modifies the original array instead of creating a new one.
Comparison Function
Comparison Function Syntax
// Compare function syntax
array.sort((a, b) => {
if (a < b) return -1; // a comes first
if (a > b) return 1; // b comes first
return 0; // equal
});This example explains how the comparison function works inside sort(). Returning a negative value places 'a' before 'b', returning a positive value places 'b' before 'a', and returning 0 keeps their order unchanged.
Return -1: a comes before b
Return 0: keep original order
Return 1: b comes before a
Examples
Sort Numbers
Sort Numbers
// Wrong - sorts as strings
const numbers = [10, 5, 40, 25];
numbers.sort();
console.log(numbers); // [10, 25, 40, 5] (wrong!)
// Correct - use comparison function
numbers.sort((a, b) => a - b);
console.log(numbers); // [5, 10, 25, 40]By default, JavaScript sorts numbers as strings which leads to incorrect results. This example shows how to use a comparison function (a - b) to correctly sort numbers in ascending order.
Sort in Descending Order
Sort in Descending Order
const numbers = [10, 5, 40, 25];
numbers.sort((a, b) => b - a);
console.log(numbers); // [40, 25, 10, 5]This example demonstrates how to sort numeric arrays in descending order by reversing the comparison logic using (b - a).
Sort Objects by Property
Sort Objects by Property
const users = [
{ name: 'Charlie', age: 30 },
{ name: 'Alice', age: 25 },
{ name: 'Bob', age: 35 }
];
users.sort((a, b) => a.age - b.age);
console.log(users);
// [Alice(25), Charlie(30), Bob(35)]This example sorts an array of objects based on the 'age' property using a comparison function.
Sort Strings Alphabetically
Sort Strings Alphabetically
const names = ['Charlie', 'Alice', 'Bob'];
names.sort((a, b) => a.localeCompare(b));
console.log(names); // ['Alice', 'Bob', 'Charlie']This example uses localeCompare() to sort strings alphabetically in a more reliable and locale-aware way.
Preserve Original Array
Preserve Original Array
const original = [3, 1, 2];
const sorted = [...original].sort((a, b) => a - b);
console.log(original); // [3, 1, 2] (unchanged)
console.log(sorted); // [1, 2, 3]Because sort() mutates the original array, this example shows how to create a copy using the spread operator before sorting.
Common Mistakes
❌ Sorting Numbers Without Comparison Function
Sorting Numbers Without Comparison Function
const nums = [10, 5, 100];
nums.sort(); // [10, 100, 5] - WRONG!
// Always use comparison function for numbers
nums.sort((a, b) => a - b); // [5, 10, 100]This example highlights a common mistake where numbers are sorted as strings, leading to incorrect order.
❌ Forgetting sort() Mutates the Original
Forgetting sort() Mutates the Original
const arr = [3, 1, 2];
const sorted = arr.sort();
console.log(arr); // [1, 2, 3] - CHANGED!
// If you need original:
const arr = [3, 1, 2];
const sorted = [...arr].sort();This example shows how the sort() method directly modifies the original array and demonstrates how to prevent that by copying the array first.
❌ Complex Comparison Without Testing
Complex Comparison Without Testing
// Test your comparison function!
const arr = [3, 1, 2];
console.log(arr.sort((a, b) => a - b)); // [1, 2, 3]
console.log(arr.sort((a, b) => b - a)); // [3, 2, 1]This example emphasizes the importance of testing comparison functions to ensure they produce the expected sorting order.
FAQs
Does sort() modify the original array?
Yes! sort() mutates the original array. Create a copy first if you need to preserve the original.
How do I sort case-insensitively?
How do I sort case-insensitively?
const names = ['charlie', 'Alice', 'BOB'];
names.sort((a, b) => a.toLowerCase().localeCompare(b.toLowerCase()));
console.log(names); // ['Alice', 'BOB', 'charlie']This example demonstrates how to perform case-insensitive string sorting by converting values to lowercase before comparing them.