Suggest an editImprove this articleRefine the answer for “sort() in an array”. Your changes go to moderation before they’re published.Approval requiredContentWhat you’re changing🇺🇸EN🇺🇦UAPreviewTitle (EN)Short answer (EN)The **`sort()`** method in JavaScript is used to sort the elements of an array. It mutates the original array (unlike most other methods) and can work with both numbers and strings if a compare function is given. **Key point:** without a compare function, `sort()` sorts elements as Unicode strings, so numbers are sorted by character, not by magnitude.Shown above the full answer for quick recall.Answer (EN)ImageThe `sort()` method in JavaScript is used to **sort the elements of an array**. It **mutates the original array** (unlike most other methods) and can work with both **numbers** and **strings** if you provide a compare function. --- ## Syntax ```javascript array.sort(compareFunction); ``` ### Where `compareFunction` is a callback of the form: ```javascript (a, b) => { // return a negative value if a should come before b // return a positive value if a should come after b // return 0 if the order doesn't matter } ``` --- ## Example 1. Simple string sorting ```javascript const fruits = ['banana', 'apple', 'cherry']; fruits.sort(); console.log(fruits); // ['apple', 'banana', 'cherry'] ``` > By default `sort()` sorts elements as **Unicode strings**, even if they are numbers! > That's why numbers without a callback are sorted **not by magnitude**, but **by character**. --- ## Example 2. A mistake when sorting numbers without a compare function ```javascript const numbers = [1, 10, 2, 5]; numbers.sort(); console.log(numbers); // [1, 10, 2, 5] - sorted as strings! ``` Fixed: ```javascript numbers.sort((a, b) => a - b); console.log(numbers); // [1, 2, 5, 10] ``` > The function `(a, b) => a - b` sorts **in ascending order**, > `(a, b) => b - a` - **in descending order**. --- ## Example 3. Sorting by an object property ```javascript const users = [ { name: 'Tim', age: 25 }, { name: 'Alex', age: 30 }, { name: 'John', age: 20 } ]; users.sort((a, b) => a.age - b.age); console.log(users); // [ // { name: 'John', age: 20 }, // { name: 'Tim', age: 25 }, // { name: 'Alex', age: 30 } // ] ``` > A common scenario is sorting an array of objects by a numeric field. --- ## Example 4. Sorting strings alphabetically (case-insensitive) ```javascript const names = ['tim', 'Alex', 'john']; names.sort((a, b) => a.localeCompare(b, 'en', { sensitivity: 'base' })); console.log(names); // ['Alex', 'john', 'tim'] ``` > `localeCompare` is the correct way to sort strings taking language and case into account. --- ## Example 5. Sorting in descending order ```javascript const prices = [100, 500, 200, 50]; prices.sort((a, b) => b - a); console.log(prices); // [500, 200, 100, 50] ``` --- ## Important: `sort()` **mutates the original array** ```javascript const arr = [3, 1, 2]; const sorted = arr.sort(); console.log(sorted); // [1, 2, 3] console.log(arr); // [1, 2, 3] - the same array, mutated! ``` > If you need to keep the original array, **copy it before sorting**: ```javascript const sortedCopy = [...arr].sort((a, b) => a - b); ``` --- ## Example 6. Sorting by multiple criteria ```javascript const users = [ { name: 'Tim', age: 25 }, { name: 'Alex', age: 25 }, { name: 'John', age: 20 } ]; users.sort((a, b) => { if (a.age !== b.age) return a.age - b.age; return a.name.localeCompare(b.name); }); console.log(users); // [ // { name: 'John', age: 20 }, // { name: 'Alex', age: 25 }, // { name: 'Tim', age: 25 } // ] ``` > If the age is the same, sorting falls back to the name. --- ## Mistakes to watch for 1. **Without a callback, strings are sorted instead of numbers** ```javascript [10, 2, 1].sort(); // ['1', '10', '2'] ``` Solution: ```javascript [10, 2, 1].sort((a, b) => a - b); // [1, 2, 10] ``` 2. **Mutating the original array** ```javascript const a = [3, 1, 2]; const b = a.sort(); console.log(a === b); // true - it's the same object ``` 3. **Lack of stability in older JS versions** > Sorting could be **unstable** in older engines (before ES2019). > In modern ECMAScript versions `sort()` is stable - elements with equal order keep their original relative position. --- ## When to use `sort()` | Goal | Is `sort()` suitable? | |---|---| | Sort numbers or strings | Yes | | Sort objects by a field | Yes | | Get a new sorted array without changing the original | Yes, but only with a copy (`[...arr]`) | | Check a condition | No | | Transform data | No | --- ## In short: > `sort()` sorts the elements of an array **in place**, by default as **strings**. > To sort numbers, provide a compare function. Memorization formula: `arr.sort((a, b) => a - b)` -> ascending `arr.sort((a, b) => b - a)` -> descending --- ## Comparison with other methods | Method | Returns a new array | Mutates the original | Purpose | |---|---|---|---| | **map()** | yes | no | Transforms elements | | **filter()** | yes | no | Selects elements | | **find()** | no (an element) | no | Finds the first matching element | | **reduce()** | no (a single value) | no | Reduces to a single result | | **sort()** | no (the same array) | yes | Sorts elements |For the reviewerNote to the moderator (optional)Visible only to the moderator. Helps review go faster.