mirror of
https://github.com/freeCodeCamp/freeCodeCamp.git
synced 2026-04-13 22:00:19 -04:00
feat(curriculum): Add interactive examples to Sort method lesson (#63404)
This commit is contained in:
@@ -5,7 +5,7 @@ challengeType: 19
|
||||
dashedName: how-does-the-sort-method-work
|
||||
---
|
||||
|
||||
# --description--
|
||||
# --interactive--
|
||||
|
||||
There are many different ways to sort your data in programming. In this lesson, we will focus on the built-in `sort` method in JavaScript.
|
||||
|
||||
@@ -27,6 +27,8 @@ const fruits = ["Banana", "Orange", "Apple", "Mango"];
|
||||
|
||||
Our goal is to sort the array in alphabetical order. We can do this by calling the `sort` method on the `fruits` array.
|
||||
|
||||
:::interactive_editor
|
||||
|
||||
```js
|
||||
const fruits = ["Banana", "Orange", "Apple", "Mango"];
|
||||
fruits.sort();
|
||||
@@ -34,6 +36,8 @@ fruits.sort();
|
||||
console.log(fruits); // ["Apple", "Banana", "Mango", "Orange"]
|
||||
```
|
||||
|
||||
:::
|
||||
|
||||
The result will be a sorted array of fruits in alphabetical order starting with the fruit `Apple`.
|
||||
|
||||
In this next example, we want to sort the following array of numbers:
|
||||
@@ -44,6 +48,8 @@ const numbers = [414, 200, 5, 10, 3];
|
||||
|
||||
If we try to use the `sort` method on this `numbers` array, we will get unexpected results.
|
||||
|
||||
:::interactive_editor
|
||||
|
||||
```js
|
||||
const numbers = [414, 200, 5, 10, 3];
|
||||
numbers.sort();
|
||||
@@ -51,6 +57,8 @@ numbers.sort();
|
||||
console.log(numbers); // [10, 200, 3, 414, 5]
|
||||
```
|
||||
|
||||
:::
|
||||
|
||||
We expected to see the result `[3, 5, 10, 200, 414]`, but instead we got `[10, 200, 3, 414, 5]`.
|
||||
|
||||
This is because the `sort` method converts the elements to strings and then compares their sequences of UTF-16 code units values.
|
||||
@@ -63,6 +71,8 @@ The solution to this problem is to provide a compare function to the `sort` meth
|
||||
|
||||
Here is an example of how to sort the `numbers` array using a compare function:
|
||||
|
||||
:::interactive_editor
|
||||
|
||||
```js
|
||||
const numbers = [414, 200, 5, 10, 3];
|
||||
|
||||
@@ -71,6 +81,8 @@ numbers.sort((a, b) => a - b);
|
||||
console.log(numbers); // [3, 5, 10, 200, 414]
|
||||
```
|
||||
|
||||
:::
|
||||
|
||||
The parameters `a` and `b` are the two elements being compared. The compare function should return a negative value if `a` should come before `b`, a positive value if `a` should come after `b`, and zero if `a` and `b` are equal.
|
||||
|
||||
The first comparison is between the numbers `414` and `200`. The result of `414 - 200` is `214`, which is a positive value. This means that `414` should come after `200` in the sorted array.
|
||||
|
||||
Reference in New Issue
Block a user