Js Array Sort in JavaScript
? JavaScript Array Sorting
Sorting Arrays in JavaScript
By default, .sort() sorts elements as strings in lexicographical order.
Basic Syntax
array.sort([compareFunction])If no
compareFunctionis provided, elements are converted to strings and sorted lexicographically.To sort numerically or by custom logic, provide a
compareFunction.
Examples
1. Sorting Strings Alphabetically
const fruits = ["banana", "apple", "cherry"];fruits.sort();console.log(fruits); // ["apple", "banana", "cherry"]2. Sorting Numbers (Ascending)
Default sort without function gives wrong results:
const nums = [10, 5, 100, 1];nums.sort();console.log(nums); // [1, 10, 100, 5] (wrong for numbers!)Use a compare function:
nums.sort((a, b) => a - b);console.log(nums); // [1, 5, 10, 100]3. Sorting Numbers (Descending)
nums.sort((a, b) => b - a);console.log(nums); // [100, 10, 5, 1]4. Sorting Array of Objects
const people = [ { name: "John", age: 30 }, { name: "Jane", age: 25 }, { name: "Bob", age: 35 }];// Sort by age ascendingpeople.sort((a, b) => a.age - b.age);console.log(people);How Compare Function Works
The compare function takes two arguments (a, b) and should return:
Negative value if
ashould come beforeb.Zero if
aandbare equal (no change).Positive value if
ashould come afterb.
Summary
| Usage | Example | Result |
|---|---|---|
| Default sort (lexicographic) | [3, 10, 1].sort() | [1, 10, 3] (unexpected) |
| Numeric ascending | .sort((a,b) => a - b) | [1, 3, 10] |
| Numeric descending | .sort((a,b) => b - a) | [10, 3, 1] |
| Sort objects by property | .sort((a,b) => a.prop - b.prop) | Sorted array of objects by prop |
Want me to show stable sorting tricks or locale-aware sorting with localeCompare?