Skip to content

Commit 2b3bebe

Browse files
committed
1-js/05-data-types/05-array-methods/
Ru translation: filter, map, sort blocks of text have been translated
1 parent d80d7bc commit 2b3bebe

1 file changed

Lines changed: 38 additions & 38 deletions

File tree

1-js/05-data-types/05-array-methods/article.md

Lines changed: 38 additions & 38 deletions
Original file line numberDiff line numberDiff line change
@@ -313,54 +313,54 @@ alert(user.name); // Вася
313313

314314
### filter
315315

316-
The `find` method looks for a single (first) element that makes the function return `true`.
316+
Метод `find` ищет один (первый) элемент, который заставляет функцию возвращать` true`.
317317

318-
If there may be many, we can use [arr.filter(fn)](mdn:js/Array/filter).
318+
Если их может быть много, мы можем использовать [arr.filter(fn)](mdn:js/Array/filter).
319319

320-
The syntax is similar to `find`, but filter continues to iterate for all array elements even if `true` is already returned:
320+
Синтаксис похож на `find`, но фильтр продолжает повторяться для всех элементов массива, даже если` true` уже возвращено:
321321

322322
```js
323323
let results = arr.filter(function(item, index, array) {
324-
// if true item is pushed to results and iteration continues
325-
// returns empty array for complete falsy scenario
324+
// Если true — элемент добавляется к результату и перебор продолжается
325+
// Возвращает пустой массив в случае если все итерации оказались ложными
326326
});
327327
```
328328

329-
For instance:
329+
Например:
330330

331331
```js run
332332
let users = [
333-
{id: 1, name: "John"},
334-
{id: 2, name: "Pete"},
335-
{id: 3, name: "Mary"}
333+
{id: 1, name: "Вася"},
334+
{id: 2, name: "Петя"},
335+
{id: 3, name: "Маша"}
336336
];
337337

338-
// returns array of the first two users
338+
// возвращает массив первых двух пользователей
339339
let someUsers = users.filter(item => item.id < 3);
340340

341341
alert(someUsers.length); // 2
342342
```
343343

344-
## Transform an array
344+
## Преобразование массива
345345

346-
This section is about the methods transforming or reordering the array.
346+
Этот раздел о методах преобразования или переупорядочения массива.
347347

348348

349349
### map
350350

351-
The [arr.map](mdn:js/Array/map) method is one of the most useful and often used.
351+
Метод [arr.map](mdn:js/Array/map) является одним из наиболее полезных и часто используемых.
352352

353-
The syntax is:
353+
Синтаксис:
354354

355355
```js
356356
let result = arr.map(function(item, index, array) {
357-
// returns the new value instead of item
357+
// возвращает новое значение вместо элемента
358358
})
359359
```
360360

361-
It calls the function for each element of the array and returns the array of results.
361+
Он вызывает функцию для каждого элемента массива и возвращает массив результатов.
362362

363-
For instance, here we transform each element into its length:
363+
Например, здесь мы преобразуем каждый элемент в его длину:
364364

365365
```js run
366366
let lengths = ["Bilbo", "Gandalf", "Nazgul"].map(item => item.length);
@@ -369,30 +369,30 @@ alert(lengths); // 5,7,6
369369

370370
### sort(fn)
371371

372-
The method [arr.sort](mdn:js/Array/sort) sorts the array *in place*.
372+
Метод [arr.sort](mdn:js/Array/sort) сортирует массив *на месте*.
373373

374-
For instance:
374+
Например:
375375

376376
```js run
377377
let arr = [ 1, 2, 15 ];
378378

379-
// the method reorders the content of arr (and returns it)
379+
// метод переупорядочивает содержимое arr (и возвращает его)
380380
arr.sort();
381381

382382
alert( arr ); // *!*1, 15, 2*/!*
383383
```
384384

385-
Did you notice anything strange in the outcome?
385+
Не заметили ничего странного в этом примере?
386386

387-
The order became `1, 15, 2`. Incorrect. But why?
387+
Порядок стал `1, 15, 2`. Неправильно. Но почему?
388388

389-
**The items are sorted as strings by default.**
389+
**По умолчанию элементы сортируются как строки.**
390390

391-
Literally, all elements are converted to strings and then compared. So, the lexicographic ordering is applied and indeed `"2" > "15"`.
391+
Это произошло потому, что все элементы преобразуются в строки, а затем сравниваются. Таким образом, применяется лексикографическое упорядочение и на самом деле `"2" > "15"`.
392392

393-
To use our own sorting order, we need to supply a function of two arguments as the argument of `arr.sort()`.
393+
Чтобы использовать наш собственный порядок сортировки, нам нужно предоставить функцию с двумя аргументами в качестве аргумента `arr.sort ()`.
394394

395-
The function should work like this:
395+
Функция должна работать так:
396396
```js
397397
function compare(a, b) {
398398
if (a > b) return 1;
@@ -401,7 +401,7 @@ function compare(a, b) {
401401
}
402402
```
403403

404-
For instance:
404+
Например:
405405

406406
```js run
407407
function compareNumeric(a, b) {
@@ -419,27 +419,27 @@ arr.sort(compareNumeric);
419419
alert(arr); // *!*1, 2, 15*/!*
420420
```
421421

422-
Now it works as intended.
422+
Теперь всё работает как надо.
423423

424-
Let's step aside and think what's happening. The `arr` can be array of anything, right? It may contain numbers or strings or html elements or whatever. We have a set of *something*. To sort it, we need an *ordering function* that knows how to compare its elements. The default is a string order.
424+
Давайте отойдем в сторону и подумаем, что же происходит. Упомянутый выше массив `arr` может быть массивом чего угодно, верно? Он может содержать числа, строки, элементы HTML или что-то еще. У нас есть набор *чего-то*. Чтобы отсортировать его, нам нужна *упорядочивающая функция*, которая знает, как сравнивать ее элементы. По умолчанию элементы сортируются как строки.
425425

426-
The `arr.sort(fn)` method has a built-in implementation of sorting algorithm. We don't need to care how it exactly works (an optimized [quicksort](https://en.wikipedia.org/wiki/Quicksort) most of the time). It will walk the array, compare its elements using the provided function and reorder them, all we need is to provide the `fn` which does the comparison.
426+
Метод `arr.sort(fn)` имеет встроенную реализацию алгоритма сортировки. Нам не нужно заботиться о том, как это на самом деле работает (в большинстве случаев это оптимизированная [quicksort](https://en.wikipedia.org/wiki/Quicksort)). Она будет проходить по массиву, сравнивать его элементы с помощью предоставленной функции и переупорядочивать их, все, что нам нужно, это предоставить `fn`, которая выполняет сравнение.
427427

428-
By the way, if we ever want to know which elements are compared -- nothing prevents from alerting them:
428+
Кстати, если мы когда-нибудь захотим узнать, какие элементы сравниваются -- ничто не мешает нам вывести их на экран:
429429

430430
```js run
431431
[1, -2, 15, 2, 0, 8].sort(function(a, b) {
432432
alert( a + " <> " + b );
433433
});
434434
```
435435

436-
The algorithm may compare an element multiple times in the process, but it tries to make as few comparisons as possible.
436+
В процессе работы алгоритм может сравнивать элемент по нескольку раз, но он всё равно старается сделать как можно меньше сравнений.
437437

438438

439-
````smart header="A comparison function may return any number"
440-
Actually, a comparison function is only required to return a positive number to say "greater" and a negative number to say "less".
439+
````smart header="Функция сравнения может вернуть любое число"
440+
На самом деле, функция сравнения требуется только для возврата положительного числа, чтобы сказать "больше" и отрицательного числа, чтобы сказать "меньше".
441441
442-
That allows to write shorter functions:
442+
Это позволяет писать более короткие функции:
443443
444444
```js run
445445
let arr = [ 1, 2, 15 ];
@@ -450,14 +450,14 @@ alert(arr); // *!*1, 2, 15*/!*
450450
```
451451
````
452452

453-
````smart header="Arrow functions for the best"
454-
Remember [arrow functions](info:function-expressions-arrows#arrow-functions)? We can use them here for neater sorting:
453+
````smart header="Лучше использовать стрелочные функции"
454+
Помните [arrow functions](info:function-expressions-arrows#arrow-functions)? Мы можем использовать их здесь для того что бы сортировка выглядела более аккуратной:
455455
456456
```js
457457
arr.sort( (a, b) => a - b );
458458
```
459459
460-
This works exactly the same as the other, longer, version above.
460+
Это работает точно так же, как и другая, более длинная версия выше.
461461
````
462462

463463
### reverse

0 commit comments

Comments
 (0)