-
Notifications
You must be signed in to change notification settings - Fork 667
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Добавляет доку про метод sort
#5135
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,115 @@ | ||
--- | ||
title: "`.sort()`" | ||
description: "Сортирует элементы массива." | ||
authors: | ||
- Maksim631 | ||
related: | ||
- js/arrays | ||
- js/element | ||
- js/math | ||
tags: | ||
- doka | ||
--- | ||
|
||
## Кратко | ||
|
||
Метод `sort()` позволяет отсортировать массив с мутированием исходного массива. По умолчанию сортировка выполняется в порядке возрастания, элементы массива приводятся к строке, и их порядок сравнивается в UTF-16 кодировке. | ||
|
||
Мы можем передать функцию-компаратор для управления алгоритмом сравнения элементов. Метод возвращает ссылку на массив. | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Мне кажется тут не совсем корректно. Алгоритм остается один и тот же, просто на каждом шаге вызывается твоя собственная функция |
||
|
||
## Пример сортировки по умолчанию | ||
|
||
```js | ||
const nums = [15, 0, 4] | ||
const strings = ['a', 'c', 'b'] | ||
nums.sort() | ||
console.log(nums) | ||
// [0, 15, 4] | ||
strings.sort() | ||
console.log(strings) | ||
// ['a', 'b', 'c'] | ||
``` | ||
|
||
## Пример сортировки с переданной функцией-компаратором | ||
|
||
```js | ||
const nums = [15, 0, 4] | ||
nums.sort((a, b) => a - b) | ||
console.log(nums) | ||
// [0, 4, 15] | ||
``` | ||
|
||
## Как пишется | ||
|
||
Метод имеет только один опциональный параметр — функцию-компаратор. | ||
|
||
```js | ||
sort() | ||
sort(compareFn) | ||
``` | ||
|
||
Функция-компаратор должна возвращать число. В функцию передаётся два аргумента `a` и `b`. Знак этого числа определяет порядок двух элементов относительно друг друга: | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Не обязательно. Вот это не бросит ошибку |
||
|
||
- Число меньше 0 означает, что элемент `a` меньше, чем элемент `b`; | ||
- Число больше 0 означает, что элемент `a` больше, чем элемент `b`; | ||
- Число равно 0 означает, что элементы равны. | ||
|
||
### Пример функции-компаратора для сортировки чисел | ||
|
||
```js | ||
function compareFn(a, b) { | ||
if (a < b) { | ||
return -1 | ||
} else if (a > b) { | ||
return 1 | ||
} | ||
// a === b | ||
return 0 | ||
} | ||
``` | ||
|
||
Так как имеет значение только знак возвращаемого значения, то можно упростить: | ||
|
||
```js | ||
function compareFn(a, b) { | ||
return a - b | ||
} | ||
``` | ||
|
||
Также можно определить с помощью стрелочной функции: | ||
|
||
```js | ||
const compareFn = (a, b) => a - b | ||
``` | ||
|
||
### Пример сортировки чисел по убыванию | ||
|
||
```js | ||
const nums = [3, 4, 0] | ||
const compareFn = (a, b) => b - a | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Это работает, но тут надо проявлять осторожность :) На случай если в массиве не только числа |
||
|
||
nums.sort(compareFn) | ||
|
||
console.log(nums) | ||
// [4, 3, 0] | ||
``` | ||
|
||
## Как понять | ||
|
||
Метод `sort()` работает так же, как и метод `toSorted()`. Основное отличие в том, что метод `sort()` мутирует исходный массив, а метод `toSorted()` возвращает новый массив, с отсортированными элементами. | ||
|
||
```js | ||
const nums = [20, 1, -10] | ||
const toSortedNums = nums.toSorted((a, b) => a - b) | ||
console.log(nums) | ||
// [20, 1, -10] | ||
console.log(toSortedNums) | ||
// [-10, 1, 20] | ||
const sortedNums = nums.sort((a, b) => a - b) | ||
console.log(nums) | ||
// [-10, 1, 20] | ||
console.log(sortedNums) | ||
// [-10, 1, 20] | ||
console.log(nums === sortedNums) | ||
// true | ||
``` |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Давай добавим важно дополнение