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
+24-24
Original file line number
Diff line number
Diff line change
@@ -1,6 +1,6 @@
1
1
# Array methods
2
2
3
-
Arrays provide a lot of methods. To make things easier, in this chapter they are split into groups.
3
+
Arrays provide a lot of methods. To make things easier, in this chapter, they are split into groups.
4
4
5
5
## Add/remove items
6
6
@@ -32,11 +32,11 @@ alert( arr.length ); // 3
32
32
33
33
The element was removed, but the array still has 3 elements, we can see that `arr.length == 3`.
34
34
35
-
That's natural, because `delete obj.key` removes a value by the `key`. It's all it does. Fine for objects. But for arrays we usually want the rest of elements to shift and occupy the freed place. We expect to have a shorter array now.
35
+
That's natural, because `delete obj.key` removes a value by the `key`. It's all it does. Fine for objects. But for arrays we usually want the rest of the elements to shift and occupy the freed place. We expect to have a shorter array now.
36
36
37
37
So, special methods should be used.
38
38
39
-
The [arr.splice](mdn:js/Array/splice) method is a swiss army knife for arrays. It can do everything: insert, remove and replace elements.
39
+
The [arr.splice](mdn:js/Array/splice) method is a Swiss army knife for arrays. It can do everything: insert, remove and replace elements.
Easy, right? Starting from the index `1` it removed `1` element.
64
64
65
-
In the next example we remove 3 elements and replace them with the other two:
65
+
In the next example, we remove 3 elements and replace them with the other two:
66
66
67
67
```js run
68
68
let arr = [*!*"I", "study", "JavaScript",*/!*"right", "now"];
@@ -84,7 +84,7 @@ let removed = arr.splice(0, 2);
84
84
alert( removed ); // "I", "study" <-- array of removed elements
85
85
```
86
86
87
-
The `splice` method is also able to insert the elements without any removals. For that we need to set `deleteCount` to `0`:
87
+
The `splice` method is also able to insert the elements without any removals. For that, we need to set `deleteCount` to `0`:
88
88
89
89
```js run
90
90
let arr = ["I", "study", "JavaScript"];
@@ -114,7 +114,7 @@ alert( arr ); // 1,2,3,4,5
114
114
115
115
### slice
116
116
117
-
The method [arr.slice](mdn:js/Array/slice) is much simpler than similar-looking `arr.splice`.
117
+
The method [arr.slice](mdn:js/Array/slice) is much simpler than the similar-looking `arr.splice`.
118
118
119
119
The syntax is:
120
120
@@ -124,7 +124,7 @@ arr.slice([start], [end])
124
124
125
125
It returns a new array copying to it all items from index `start` to `end` (not including `end`). Both `start` and `end` can be negative, in that case position from array end is assumed.
126
126
127
-
It's similar to a string method `str.slice`, but instead of substrings it makes subarrays.
127
+
It's similar to a string method `str.slice`, but instead of substrings, it makes subarrays.
128
128
129
129
For instance:
130
130
@@ -206,7 +206,7 @@ The [arr.forEach](mdn:js/Array/forEach) method allows to run a function for ever
206
206
The syntax:
207
207
```js
208
208
arr.forEach(function(item, index, array) {
209
-
// ... do something with item
209
+
// ... do something with an item
210
210
});
211
211
```
212
212
@@ -239,7 +239,7 @@ The methods [arr.indexOf](mdn:js/Array/indexOf) and [arr.includes](mdn:js/Array/
239
239
-`arr.indexOf(item, from)` -- looks for `item` starting from index `from`, and returns the index where it was found, otherwise `-1`.
240
240
-`arr.includes(item, from)` -- looks for `item` starting from index `from`, returns `true` if found.
241
241
242
-
Usually these methods are used with only one argument: the `item` to search. By default, the search is from the beginning.
242
+
Usually, these methods are used with only one argument: the `item` to search. By default, the search is from the beginning.
Please note that `indexOf` uses the strict equality `===` for comparison. So, if we look for `false`, it finds exactly `false` and not the zero.
257
257
258
-
If we want to check if `item` exists in the array, and don't need the index, then `arr.includes` is preferred.
258
+
If we want to check if `item` exists in the array and don't need the index, then `arr.includes` is preferred.
259
259
260
260
The method [arr.lastIndexOf](mdn:js/Array/lastIndexOf) is the same as `indexOf`, but looks for from right to left.
261
261
@@ -274,12 +274,12 @@ const arr = [NaN];
274
274
alert( arr.indexOf(NaN) ); // -1 (wrong, should be 0)
275
275
alert( arr.includes(NaN) );// true (correct)
276
276
```
277
-
That's because `includes` was added to JavaScript much later and uses the more up to date comparison algorithm internally.
277
+
That's because `includes` was added to JavaScript much later and uses the more up-to-date comparison algorithm internally.
278
278
````
279
279
280
280
### find and findIndex/findLastIndex
281
281
282
-
Imagine we have an array of objects. How do we find an object with the specific condition?
282
+
Imagine we have an array of objects. How do we find an object with a specific condition?
283
283
284
284
Here the [arr.find(fn)](mdn:js/Array/find) method comes in handy.
285
285
@@ -297,7 +297,7 @@ The function is called for elements of the array, one after another:
297
297
- `index` is its index.
298
298
- `array` is the array itself.
299
299
300
-
If it returns `true`, the search is stopped, the `item` is returned. If nothing found, `undefined` is returned.
300
+
If it returns `true`, the search is stopped, the `item` is returned. If nothing is found, `undefined` is returned.
301
301
302
302
For example, we have an array of users, each with the fields `id` and `name`. Let's find the one with `id == 1`:
303
303
@@ -313,11 +313,11 @@ let user = users.find(item => item.id == 1);
313
313
alert(user.name); // John
314
314
```
315
315
316
-
In real life arrays of objects is a common thing, so the `find` method is very useful.
316
+
In real life, arrays of objects are a common thing, so the `find` method is very useful.
317
317
318
318
Note that in the example we provide to `find` the function `item => item.id == 1` with one argument. That's typical, other arguments of this function are rarely used.
319
319
320
-
The [arr.findIndex](mdn:js/Array/findIndex) method has the same syntax, but returns the index where the element was found instead of the element itself. The value of `-1` is returned if nothing is found.
320
+
The [arr.findIndex](mdn:js/Array/findIndex) method has the same syntax but returns the index where the element was found instead of the element itself. The value of `-1` is returned if nothing is found.
321
321
322
322
The [arr.findLastIndex](mdn:js/Array/findLastIndex) method is like `findIndex`, but searches from right to left, similar to `lastIndexOf`.
Let's step aside and think what's happening. The `arr` can be array of anything, right? It may contain numbers or strings or objects or whatever. We have a set of *some items*. To sort it, we need an *ordering function* that knows how to compare its elements. The default is a string order.
453
+
Let's step aside and think about what's happening. The `arr` can be an array of anything, right? It may contain numbers or strings or objects or whatever. We have a set of *some items*. To sort it, we need an *ordering function* that knows how to compare its elements. The default is a string order.
454
454
455
455
The `arr.sort(fn)` method implements a generic sorting algorithm. We don't need to care how it internally works (an optimized [quicksort](https://en.wikipedia.org/wiki/Quicksort) or [Timsort](https://en.wikipedia.org/wiki/Timsort) 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.
456
456
457
-
By the way, if we ever want to know which elements are compared -- nothing prevents from alerting them:
457
+
By the way, if we ever want to know which elements are compared -- nothing prevents us from alerting them:
458
458
459
459
```js run
460
460
[1, -2, 15, 2, 0, 8].sort(function(a, b) {
@@ -526,7 +526,7 @@ Here's the situation from real life. We are writing a messaging app, and the per
526
526
527
527
The [str.split(delim)](mdn:js/String/split) method does exactly that. It splits the string into an array by the given delimiter `delim`.
528
528
529
-
In the example below, we split by a comma followed by space:
529
+
In the example below, we split by a comma followed by a space:
530
530
531
531
```js run
532
532
let names = 'Bilbo, Gandalf, Nazgul';
@@ -593,9 +593,9 @@ Arguments:
593
593
-`index` -- is its position.
594
594
-`array` -- is the array.
595
595
596
-
As function is applied, the result of the previous function call is passed to the next one as the first argument.
596
+
As the function is applied, the result of the previous function call is passed to the next one as the first argument.
597
597
598
-
So, the first argument is essentially the accumulator that stores the combined result of all previous executions. And at the end it becomes the result of `reduce`.
598
+
So, the first argument is essentially the accumulator that stores the combined result of all previous executions. And at the end, it becomes the result of `reduce`.
599
599
600
600
Sounds complicated?
601
601
@@ -664,7 +664,7 @@ arr.reduce((sum, current) => sum + current);
664
664
665
665
So it's advised to always specify the initial value.
666
666
667
-
The method [arr.reduceRight](mdn:js/Array/reduceRight) does the same, but goes from right to left.
667
+
The method [arr.reduceRight](mdn:js/Array/reduceRight) does the same but goes from right to left.
Almost all array methods that call functions -- like `find`, `filter`, `map`, with a notable exception of `sort`, accept an optional additional parameter `thisArg`.
691
691
692
-
That parameter is not explained in the sections above, because it's rarely used. But for completeness we have to cover it.
692
+
That parameter is not explained in the sections above, because it's rarely used. But for completeness, we have to cover it.
693
693
694
694
Here's the full syntax of these methods:
695
695
@@ -749,7 +749,7 @@ A cheat sheet of array methods:
749
749
-`concat(...items)` -- returns a new array: copies all members of the current one and adds `items` to it. If any of `items` is an array, then its elements are taken.
750
750
751
751
- To search among elements:
752
-
-`indexOf/lastIndexOf(item, pos)` -- look for `item` starting from position `pos`, return the index or `-1` if not found.
752
+
-`indexOf/lastIndexOf(item, pos)` -- look for `item` starting from position `pos`, and return the index or `-1` if not found.
753
753
-`includes(value)` -- returns `true` if the array has `value`, otherwise `false`.
754
754
-`find/filter(func)` -- filter elements through the function, return first/all values that make it return `true`.
755
755
-`findIndex` is like `find`, but returns the index instead of a value.
@@ -795,7 +795,7 @@ These methods are the most used ones, they cover 99% of use cases. But there are
795
795
796
796
For the full list, see the [manual](mdn:js/Array).
797
797
798
-
From the first sight it may seem that there are so many methods, quite difficult to remember. But actually that's much easier.
798
+
At first sight, it may seem that there are so many methods, quite difficult to remember. But actually, that's much easier.
799
799
800
800
Look through the cheat sheet just to be aware of them. Then solve the tasks of this chapter to practice, so that you have experience with array methods.
0 commit comments