minor
This commit is contained in:
parent
84fbfea996
commit
a8f90e8e9f
2 changed files with 52 additions and 52 deletions
|
@ -122,26 +122,23 @@ The syntax is:
|
|||
arr.slice(start, end)
|
||||
```
|
||||
|
||||
It returns a new array containing 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.
|
||||
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.
|
||||
|
||||
It works like `str.slice`, but makes subarrays instead of substrings.
|
||||
It's similar to a string method `str.slice`, but instead of substringss it makes subarrays.
|
||||
|
||||
For instance:
|
||||
|
||||
```js run
|
||||
let str = "test";
|
||||
let arr = ["t", "e", "s", "t"];
|
||||
|
||||
alert( str.slice(1, 3) ); // es
|
||||
alert( arr.slice(1, 3) ); // e,s
|
||||
alert( arr.slice(1, 3) ); // e,s (copy from 1 to 3)
|
||||
|
||||
alert( str.slice(-2) ); // st
|
||||
alert( arr.slice(-2) ); // s,t
|
||||
alert( arr.slice(-2) ); // s,t (copy from -2 till the end)
|
||||
```
|
||||
|
||||
### concat
|
||||
|
||||
The method [arr.concat](mdn:js/Array/concat) joins the array with other arrays and/or items.
|
||||
The method [arr.concat](mdn:js/Array/concat) creates a new array that includes values from other arrays and additional items.
|
||||
|
||||
The syntax is:
|
||||
|
||||
|
@ -153,24 +150,24 @@ It accepts any number of arguments -- either arrays or values.
|
|||
|
||||
The result is a new array containing items from `arr`, then `arg1`, `arg2` etc.
|
||||
|
||||
If an argument is an array or has `Symbol.isConcatSpreadable` property, then all its elements are copied. Otherwise, the argument itself is copied.
|
||||
If an argument `argN` is an array, then all its elements are copied. Otherwise, the argument itself is copied.
|
||||
|
||||
For instance:
|
||||
|
||||
```js run
|
||||
let arr = [1, 2];
|
||||
|
||||
// merge arr with [3,4]
|
||||
// create an array from: arr and [3,4]
|
||||
alert( arr.concat([3, 4])); // 1,2,3,4
|
||||
|
||||
// merge arr with [3,4] and [5,6]
|
||||
// create an array from: arr and [3,4] and [5,6]
|
||||
alert( arr.concat([3, 4], [5, 6])); // 1,2,3,4,5,6
|
||||
|
||||
// merge arr with [3,4], then add values 5 and 6
|
||||
// create an array from: arr and [3,4], then add values 5 and 6
|
||||
alert( arr.concat([3, 4], 5, 6)); // 1,2,3,4,5,6
|
||||
```
|
||||
|
||||
Normally, it only copies elements from arrays ("spreads" them). Other objects, even if they look like arrays, added as a whole:
|
||||
Normally, it only copies elements from arrays. Other objects, even if they look like arrays, added as a whole:
|
||||
|
||||
```js run
|
||||
let arr = [1, 2];
|
||||
|
@ -184,7 +181,7 @@ alert( arr.concat(arrayLike) ); // 1,2,[object Object]
|
|||
//[1, 2, arrayLike]
|
||||
```
|
||||
|
||||
...But if an array-like object has `Symbol.isConcatSpreadable` property, then its elements are added instead:
|
||||
...But if an array-like object has a special property `Symbol.isConcatSpreadable` property, the it's treated as array by `concat`: its elements are added instead:
|
||||
|
||||
```js run
|
||||
let arr = [1, 2];
|
||||
|
@ -232,7 +229,7 @@ The result of the function (if it returns any) is thrown away and ignored.
|
|||
|
||||
## Searching in array
|
||||
|
||||
These are methods to search for something in an array.
|
||||
Now let's cover methods that search in an array.
|
||||
|
||||
### indexOf/lastIndexOf and includes
|
||||
|
||||
|
@ -280,7 +277,7 @@ let result = arr.find(function(item, index, array) {
|
|||
});
|
||||
```
|
||||
|
||||
The function is called repetitively for each element of the array:
|
||||
The function is called for elements of the array, one after another:
|
||||
|
||||
- `item` is the element.
|
||||
- `index` is its index.
|
||||
|
@ -304,7 +301,7 @@ alert(user.name); // John
|
|||
|
||||
In real life arrays of objects is a common thing, so the `find` method is very useful.
|
||||
|
||||
Note that in the example we provide to `find` the function `item => item.id == 1` with one argument. Other arguments of this function are rarely used.
|
||||
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.
|
||||
|
||||
The [arr.findIndex](mdn:js/Array/findIndex) method is essentially the same, but it returns the index where the element was found instead of the element itself and `-1` is returned when nothing is found.
|
||||
|
||||
|
@ -314,12 +311,12 @@ The `find` method looks for a single (first) element that makes the function ret
|
|||
|
||||
If there may be many, we can use [arr.filter(fn)](mdn:js/Array/filter).
|
||||
|
||||
The syntax is similar to `find`, but filter continues to iterate for all array elements even if `true` is already returned:
|
||||
The syntax is similar to `find`, but `filter` returns an array of all matching elements:
|
||||
|
||||
```js
|
||||
let results = arr.filter(function(item, index, array) {
|
||||
// if true item is pushed to results and iteration continues
|
||||
// returns empty array for complete falsy scenario
|
||||
// if true item is pushed to results and the iteration continues
|
||||
// returns empty array if nothing found
|
||||
});
|
||||
```
|
||||
|
||||
|
@ -340,23 +337,22 @@ alert(someUsers.length); // 2
|
|||
|
||||
## Transform an array
|
||||
|
||||
This section is about the methods transforming or reordering the array.
|
||||
|
||||
Let's move on to methods that transform and reorder an array.
|
||||
|
||||
### map
|
||||
|
||||
The [arr.map](mdn:js/Array/map) method is one of the most useful and often used.
|
||||
|
||||
It calls the function for each element of the array and returns the array of results.
|
||||
|
||||
The syntax is:
|
||||
|
||||
```js
|
||||
let result = arr.map(function(item, index, array) {
|
||||
// returns the new value instead of item
|
||||
})
|
||||
});
|
||||
```
|
||||
|
||||
It calls the function for each element of the array and returns the array of results.
|
||||
|
||||
For instance, here we transform each element into its length:
|
||||
|
||||
```js run
|
||||
|
@ -366,14 +362,16 @@ alert(lengths); // 5,7,6
|
|||
|
||||
### sort(fn)
|
||||
|
||||
The method [arr.sort](mdn:js/Array/sort) sorts the array *in place*.
|
||||
The call to [arr.sort()](mdn:js/Array/sort) sorts the array *in place*, changing its element order.
|
||||
|
||||
It also returns the sorted array, but the returned value is usually ignored, as `arr` itself is modified.
|
||||
|
||||
For instance:
|
||||
|
||||
```js run
|
||||
let arr = [ 1, 2, 15 ];
|
||||
|
||||
// the method reorders the content of arr (and returns it)
|
||||
// the method reorders the content of arr
|
||||
arr.sort();
|
||||
|
||||
alert( arr ); // *!*1, 15, 2*/!*
|
||||
|
@ -385,20 +383,20 @@ The order became `1, 15, 2`. Incorrect. But why?
|
|||
|
||||
**The items are sorted as strings by default.**
|
||||
|
||||
Literally, all elements are converted to strings and then compared. So, the lexicographic ordering is applied and indeed `"2" > "15"`.
|
||||
Literally, all elements are converted to strings for comparisons. For strings, lexicographic ordering is applied and indeed `"2" > "15"`.
|
||||
|
||||
To use our own sorting order, we need to supply a function of two arguments as the argument of `arr.sort()`.
|
||||
To use our own sorting order, we need to supply a function as the argument of `arr.sort()`.
|
||||
|
||||
The function should work like this:
|
||||
The function should compare two arbitrary values and return:
|
||||
```js
|
||||
function compare(a, b) {
|
||||
if (a > b) return 1;
|
||||
if (a == b) return 0;
|
||||
if (a < b) return -1;
|
||||
if (a > b) return 1; // if the first value is greater than the second
|
||||
if (a == b) return 0; // if values are equal
|
||||
if (a < b) return -1; // if the first value is less than the second
|
||||
}
|
||||
```
|
||||
|
||||
For instance:
|
||||
For instance, to sort as numbers:
|
||||
|
||||
```js run
|
||||
function compareNumeric(a, b) {
|
||||
|
@ -418,9 +416,9 @@ alert(arr); // *!*1, 2, 15*/!*
|
|||
|
||||
Now it works as intended.
|
||||
|
||||
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.
|
||||
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.
|
||||
|
||||
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.
|
||||
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) 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.
|
||||
|
||||
By the way, if we ever want to know which elements are compared -- nothing prevents from alerting them:
|
||||
|
||||
|
@ -430,7 +428,7 @@ By the way, if we ever want to know which elements are compared -- nothing preve
|
|||
});
|
||||
```
|
||||
|
||||
The algorithm may compare an element multiple times in the process, but it tries to make as few comparisons as possible.
|
||||
The algorithm may compare an element with multiple others in the process, but it tries to make as few comparisons as possible.
|
||||
|
||||
|
||||
````smart header="A comparison function may return any number"
|
||||
|
@ -454,7 +452,7 @@ Remember [arrow functions](info:function-expressions-arrows#arrow-functions)? We
|
|||
arr.sort( (a, b) => a - b );
|
||||
```
|
||||
|
||||
This works exactly the same as the other, longer, version above.
|
||||
This works exactly the same as the longer version above.
|
||||
````
|
||||
|
||||
### reverse
|
||||
|
@ -508,14 +506,14 @@ alert( str.split('') ); // t,e,s,t
|
|||
```
|
||||
````
|
||||
|
||||
The call [arr.join(separator)](mdn:js/Array/join) does the reverse to `split`. It creates a string of `arr` items glued by `separator` between them.
|
||||
The call [arr.join(glue)](mdn:js/Array/join) does the reverse to `split`. It creates a string of `arr` items joined by `glue` between them.
|
||||
|
||||
For instance:
|
||||
|
||||
```js run
|
||||
let arr = ['Bilbo', 'Gandalf', 'Nazgul'];
|
||||
|
||||
let str = arr.join(';');
|
||||
let str = arr.join(';'); // glue the array into a string using ;
|
||||
|
||||
alert( str ); // Bilbo;Gandalf;Nazgul
|
||||
```
|
||||
|
@ -533,18 +531,21 @@ The syntax is:
|
|||
```js
|
||||
let value = arr.reduce(function(previousValue, item, index, array) {
|
||||
// ...
|
||||
}, initial);
|
||||
}, [initial]);
|
||||
```
|
||||
|
||||
The function is applied to the elements. You may notice the familiar arguments, starting from the 2nd:
|
||||
The function is applied to all array elements one after another and "carries on" its result to the next call.
|
||||
|
||||
Arguments:
|
||||
|
||||
- `previousValue` -- is the result of the previous function call, equals `initial` the first time (if `initial` is provided).
|
||||
- `item` -- is the current array item.
|
||||
- `index` -- is its position.
|
||||
- `array` -- is the array.
|
||||
|
||||
So far, like `forEach/map`. But there's one more argument:
|
||||
As function is applied, the result of the previous function call is passed to the next one as the first argument.
|
||||
|
||||
- `previousValue` -- is the result of the previous function call, `initial` for the first call.
|
||||
Sounds complicated, but it's not if you think about the first argument as the "accumulator" that stores the combined result of all previous execution. And at the end it becomes the result of `reduce`.
|
||||
|
||||
The easiest way to grasp that is by example.
|
||||
|
||||
|
@ -558,11 +559,11 @@ let result = arr.reduce((sum, current) => sum + current, 0);
|
|||
alert(result); // 15
|
||||
```
|
||||
|
||||
Here we used the most common variant of `reduce` which uses only 2 arguments.
|
||||
The function passed to `reduce` uses only 2 arguments, that's typically enough.
|
||||
|
||||
Let's see the details of what's going on.
|
||||
|
||||
1. On the first run, `sum` is the initial value (the last argument of `reduce`), equals `0`, and `current` is the first array element, equals `1`. So the result is `1`.
|
||||
1. On the first run, `sum` is the `initial` value (the last argument of `reduce`), equals `0`, and `current` is the first array element, equals `1`. So the function result is `1`.
|
||||
2. On the second run, `sum = 1`, we add the second array element (`2`) to it and return.
|
||||
3. On the 3rd run, `sum = 3` and we add one more element to it, and so on...
|
||||
|
||||
|
@ -697,7 +698,7 @@ A cheat sheet of array methods:
|
|||
- `includes(value)` -- returns `true` if the array has `value`, otherwise `false`.
|
||||
- `find/filter(func)` -- filter elements through the function, return first/all values that make it return `true`.
|
||||
- `findIndex` is like `find`, but returns the index instead of a value.
|
||||
|
||||
|
||||
- To iterate over elements:
|
||||
- `forEach(func)` -- calls `func` for every element, does not return anything.
|
||||
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue