|
1 | 1 | ---
|
2 | 2 | Title: '.sort()'
|
3 |
| -Description: 'Returns an array with its items sorted in place.' |
| 3 | +Description: 'Sorts the elements of an array in place.' |
4 | 4 | Subjects:
|
5 |
| - - 'Web Development' |
6 | 5 | - 'Computer Science'
|
| 6 | + - 'Web Development' |
7 | 7 | Tags:
|
8 | 8 | - 'Arrays'
|
9 |
| - - 'Comparison' |
10 | 9 | - 'Functions'
|
11 | 10 | - 'Methods'
|
12 |
| - - 'Sort' |
13 |
| - - 'Unicode' |
| 11 | + - 'Values' |
14 | 12 | CatalogContent:
|
15 | 13 | - 'introduction-to-javascript'
|
16 | 14 | - 'paths/front-end-engineer-career-path'
|
17 | 15 | ---
|
18 | 16 |
|
19 |
| -The **`.sort()`** method returns an array with its items sorted in place. |
| 17 | +The JS **`.sort()`** [method](https://www.codecademy.com/resources/docs/javascript/methods) is used to sort the elements of an array in place. By default, it sorts elements as [strings](https://www.codecademy.com/resources/docs/javascript/strings) in ascending order. However, a custom comparison [function](https://www.codecademy.com/resources/docs/javascript/functions) can be provided to achieve more advanced sorting. |
20 | 18 |
|
21 |
| -## Syntax |
| 19 | +## JS `.sort()` Syntax |
22 | 20 |
|
23 | 21 | ```pseudo
|
24 |
| -// No parameters |
25 |
| -array.sort(); |
26 |
| -
|
27 |
| -// With optional function |
28 |
| -array.sort((firstElement, secondElement) => { /* function body */ }; |
| 22 | +arr.sort(compareFn) |
29 | 23 | ```
|
30 | 24 |
|
31 |
| -If the `.sort()` method is used with no arguments, all items with `undefined` values are shifted to the end of the array while the remaining items are converted to [strings](https://www.codecademy.com/resources/docs/javascript/strings) and sorted by [Unicode code point value](https://en.wikipedia.org/wiki/Code_point). |
| 25 | +**Parameters:** |
32 | 26 |
|
33 |
| -An optional function is used to define how items are sorted. This is done by iterating over the `array` and comparing every `firstElement` and `secondElement` in the `/* function body */`. |
| 27 | +- `compareFn` (Optional): A function that defines the sort order. It takes two arguments, `a` and `b`, and should return: |
| 28 | + - A negative value if `a` should come before `b` |
| 29 | + - `0` if `a` and `b` are considered equal |
| 30 | + - A positive value if `a` should come after `b` |
34 | 31 |
|
35 |
| -## Example |
| 32 | +**Return value:** |
36 | 33 |
|
37 |
| -In the following example, the `.sort()` method is applied to two arrays, `letters` and `numbers` (a mix of floats and integers): |
| 34 | +JS `.sort()` returns the original array with its elements sorted in the given order. |
38 | 35 |
|
39 |
| -```js |
40 |
| -const letters = ['d', 'b', 'e', 'a', 'c']; |
41 |
| -const numbers = [5, 2, 123, 5.01, 43.5]; |
| 36 | +## Example 1: Sorting Array of Strings Using JS `.sort()` |
42 | 37 |
|
43 |
| -console.log('Letters: ', letters.sort()); |
44 |
| -console.log('Numbers: ', numbers.sort()); |
| 38 | +This example uses JS `.sort()` to sort an array of strings: |
| 39 | + |
| 40 | +```js |
| 41 | +const fruits = ['banana', 'apple', 'cherry', 'date']; |
| 42 | +fruits.sort(); |
| 43 | +console.log(fruits); |
45 | 44 | ```
|
46 | 45 |
|
47 |
| -This results in the following output: |
| 46 | +Here is the output: |
48 | 47 |
|
49 | 48 | ```shell
|
50 |
| -Letters: [ 'a', 'b', 'c', 'd', 'e' ] |
51 |
| -Numbers: [ 123, 2, 43.5, 45, 5, 5.01 ] |
| 49 | +[ 'apple', 'banana', 'cherry', 'date' ] |
52 | 50 | ```
|
53 | 51 |
|
54 |
| -The `letters` were sorted in alphabetical order. The items in `numbers` were sorted based on the leading number in the item's value (e.g., their Unicode value). Sorting numerical values more strictly requires a custom comparison function. |
| 52 | +## Example 2: Sorting Array of Numbers Using JS `.sort()` |
55 | 53 |
|
56 |
| -## Codebyte Example |
| 54 | +This example uses JS `.sort()` with a comparison function to sort an array of numbers: |
57 | 55 |
|
58 |
| -The following example showcases how the optional `callback` argument can be used to sort a `numbers` array in ascending and descending order: |
| 56 | +```js |
| 57 | +const numbers = [10, 5, 20, 1, 100]; |
| 58 | +numbers.sort((a, b) => a - b); |
| 59 | +console.log(numbers); |
| 60 | +``` |
| 61 | + |
| 62 | +Here is the output: |
| 63 | + |
| 64 | +```shell |
| 65 | +[ 1, 5, 10, 20, 100 ] |
| 66 | +``` |
| 67 | + |
| 68 | +## Codebyte Example: Sorting Array of Objects Using JS `.sort()` |
| 69 | + |
| 70 | +This codebyte example uses JS `.sort()` to sort an array of objects: |
59 | 71 |
|
60 | 72 | ```codebyte/javascript
|
61 |
| -const numbers = [5, 2, 123, 5.01, 43.5]; |
| 73 | +const users = [ |
| 74 | + { name: "Alice", age: 25 }, |
| 75 | + { name: "Bob", age: 20 }, |
| 76 | + { name: "Charlie", age: 30 } |
| 77 | +]; |
| 78 | +
|
| 79 | +users.sort((a, b) => a.age - b.age); |
62 | 80 |
|
63 |
| -const ascending = numbers.sort((a, b) => a - b); |
64 |
| -console.log("Ascending order: ", ascending); |
| 81 | +console.log(users); |
| 82 | +``` |
| 83 | + |
| 84 | +## Frequently Asked Questions |
| 85 | + |
| 86 | +### 1. How do I sort numbers in descending order using JS `.sort()`? |
| 87 | + |
| 88 | +You can reverse the comparison in your function in JS `.sort()` to sort numbers in descending order: |
| 89 | + |
| 90 | +```js |
| 91 | +numbers.sort((a, b) => b - a); |
| 92 | +``` |
| 93 | + |
| 94 | +### 2. Can I use `sort()` on a string? |
65 | 95 |
|
66 |
| -const descending = numbers.sort((a, b) => b - a); |
67 |
| -console.log("Descending order: ", descending); |
| 96 | +No. The `sort()` method is only available on arrays, not on strings. If you want to sort the characters of a string, you first need to convert it into an array (for example, using `split()`), apply `sort()`, and then join it back: |
| 97 | + |
| 98 | +```js |
| 99 | +const str = 'hello'; |
| 100 | +const sorted = str.split('').sort().join(''); |
| 101 | +console.log(sorted); // "ehllo" |
| 102 | +``` |
| 103 | + |
| 104 | +### 3. What happens when `sort()` is used in a list (array)? |
| 105 | + |
| 106 | +When you call `sort()` on an array, JavaScript converts the elements to strings by default and compares them in Unicode code point order. This means that numbers may not sort as you expect: |
| 107 | + |
| 108 | +```js |
| 109 | +const numbers = [10, 1, 5]; |
| 110 | +console.log(numbers.sort()); // [1, 10, 5] (string comparison) |
68 | 111 | ```
|
0 commit comments