Skip to content
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

Closed
wants to merge 2 commits into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
115 changes: 115 additions & 0 deletions js/array-sort/index.md
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 кодировке.
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Давай добавим важно дополнение

The sort must be stable


Мы можем передать функцию-компаратор для управления алгоритмом сравнения элементов. Метод возвращает ссылку на массив.
Copy link
Member

Choose a reason for hiding this comment

The 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`. Знак этого числа определяет порядок двух элементов относительно друг друга:
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Не обязательно. Вот это не бросит ошибку
[1,2,3].sort(() => undefined)


- Число меньше 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
Copy link
Member

Choose a reason for hiding this comment

The 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
```
Loading