You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: 1-js/05-data-types/05-array-methods/article.md
+38-38Lines changed: 38 additions & 38 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -313,54 +313,54 @@ alert(user.name); // Вася
313
313
314
314
### filter
315
315
316
-
The`find`method looks for a single (first) element that makes the function return `true`.
316
+
Метод`find`ищет один (первый) элемент, который заставляет функцию возвращать`true`.
317
317
318
-
If there may be many, we can use[arr.filter(fn)](mdn:js/Array/filter).
318
+
Если их может быть много, мы можем использовать[arr.filter(fn)](mdn:js/Array/filter).
319
319
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`уже возвращено:
321
321
322
322
```js
323
323
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
+
//Возвращает пустой массив в случае если все итерации оказались ложными
326
326
});
327
327
```
328
328
329
-
For instance:
329
+
Например:
330
330
331
331
```js run
332
332
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:"Маша"}
336
336
];
337
337
338
-
//returns array of the first two users
338
+
//возвращает массив первых двух пользователей
339
339
let someUsers =users.filter(item=>item.id<3);
340
340
341
341
alert(someUsers.length); // 2
342
342
```
343
343
344
-
## Transform an array
344
+
## Преобразование массива
345
345
346
-
This section is about the methods transforming or reordering the array.
346
+
Этот раздел о методах преобразования или переупорядочения массива.
347
347
348
348
349
349
### map
350
350
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)является одним из наиболее полезных и часто используемых.
352
352
353
-
The syntax is:
353
+
Синтаксис:
354
354
355
355
```js
356
356
let result =arr.map(function(item, index, array) {
357
-
//returns the new value instead of item
357
+
//возвращает новое значение вместо элемента
358
358
})
359
359
```
360
360
361
-
It calls the function for each element of the array and returns the array of results.
361
+
Он вызывает функцию для каждого элемента массива и возвращает массив результатов.
362
362
363
-
For instance, here we transform each element into its length:
363
+
Например, здесь мы преобразуем каждый элемент в его длину:
364
364
365
365
```js run
366
366
let lengths = ["Bilbo", "Gandalf", "Nazgul"].map(item=>item.length);
@@ -369,30 +369,30 @@ alert(lengths); // 5,7,6
369
369
370
370
### sort(fn)
371
371
372
-
The method [arr.sort](mdn:js/Array/sort)sorts the array *in place*.
372
+
Метод [arr.sort](mdn:js/Array/sort)сортирует массив *на месте*.
373
373
374
-
For instance:
374
+
Например:
375
375
376
376
```js run
377
377
let arr = [ 1, 2, 15 ];
378
378
379
-
//the method reorders the content of arr (and returns it)
379
+
//метод переупорядочивает содержимое arr (и возвращает его)
380
380
arr.sort();
381
381
382
382
alert( arr ); // *!*1, 15, 2*/!*
383
383
```
384
384
385
-
Did you notice anything strange in the outcome?
385
+
Не заметили ничего странного в этом примере?
386
386
387
-
The order became `1, 15, 2`. Incorrect. But why?
387
+
Порядок стал `1, 15, 2`. Неправильно. Но почему?
388
388
389
-
**The items are sorted as strings by default.**
389
+
**По умолчанию элементы сортируются как строки.**
390
390
391
-
Literally, all elements are converted to strings and then compared. So, the lexicographic ordering is applied and indeed`"2" > "15"`.
391
+
Это произошло потому, что все элементы преобразуются в строки, а затем сравниваются. Таким образом, применяется лексикографическое упорядочение и на самом деле`"2" > "15"`.
392
392
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()`.
394
394
395
-
The function should work like this:
395
+
Функция должна работать так:
396
396
```js
397
397
functioncompare(a, b) {
398
398
if (a > b) return1;
@@ -401,7 +401,7 @@ function compare(a, b) {
401
401
}
402
402
```
403
403
404
-
For instance:
404
+
Например:
405
405
406
406
```js run
407
407
functioncompareNumeric(a, b) {
@@ -419,27 +419,27 @@ arr.sort(compareNumeric);
419
419
alert(arr); // *!*1, 2, 15*/!*
420
420
```
421
421
422
-
Now it works as intended.
422
+
Теперь всё работает как надо.
423
423
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 или что-то еще. У нас есть набор *чего-то*. Чтобы отсортировать его, нам нужна *упорядочивающая функция*, которая знает, как сравнивать ее элементы. По умолчанию элементы сортируются как строки.
425
425
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`, которая выполняет сравнение.
427
427
428
-
By the way, if we ever want to know which elements are compared -- nothing prevents from alerting them:
428
+
Кстати, если мы когда-нибудь захотим узнать, какие элементы сравниваются -- ничто не мешает нам вывести их на экран:
429
429
430
430
```js run
431
431
[1, -2, 15, 2, 0, 8].sort(function(a, b) {
432
432
alert( a +" <> "+ b );
433
433
});
434
434
```
435
435
436
-
The algorithm may compare an element multiple times in the process, but it tries to make as few comparisons as possible.
436
+
В процессе работы алгоритм может сравнивать элемент по нескольку раз, но он всё равно старается сделать как можно меньше сравнений.
437
437
438
438
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
+
На самом деле, функция сравнения требуется только для возврата положительного числа, чтобы сказать "больше" и отрицательного числа, чтобы сказать "меньше".
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)? Мы можем использовать их здесь для того что бы сортировка выглядела более аккуратной:
455
455
456
456
```js
457
457
arr.sort( (a, b) => a - b );
458
458
```
459
459
460
-
This works exactly the same as the other, longer, version above.
460
+
Это работает точно так же, как и другая, более длинная версия выше.
0 commit comments