Which of the following method call gives the position of X that occurs after?
That’s natural, because 3 removes a value by the 4. 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. Show So, special methods should be used. The arr.splice method is a swiss army knife for arrays. It can do everything: insert, remove and replace elements. The syntax is:
It modifies 5 starting from the index 6: removes 7 elements and then inserts 8 at their place. Returns the array of removed elements.This method is easy to grasp by examples. Let’s start with the deletion:
Easy, right? Starting from the index 9 it removed 9 element.In the next example we remove 3 elements and replace them with the other two:
Here we can see that 1 returns the array of removed elements:
The 1 method is also able to insert the elements without any removals. For that we need to set 7 to 4:
Negative indexes allowed Here and in other array methods, negative indexes are allowed. They specify the position from the end of the array, like here:
sliceThe method arr.slice is much simpler than similar-looking 5.The syntax is:
It returns a new array copying to it all items from index 6 to 7 (not including 7). Both 6 and 7 can be negative, in that case position from array end is assumed.It’s similar to a string method 1, but instead of substrings it makes subarrays.For instance:
We can also call it without arguments: 2 creates a copy of 5. That’s often used to obtain a copy for further transformations that should not affect the original array.concatThe method arr.concat creates a new array that includes values from other arrays and additional items. The syntax is:
It accepts any number of arguments – either arrays or values. The result is a new array containing items from 5, then 5, 6 etc.If an argument 7 is an array, then all its elements are copied. Otherwise, the argument itself is copied.For instance: 0Normally, it only copies elements from arrays. Other objects, even if they look like arrays, are added as a whole: 1…But if an array-like object has a special 8 property, then it’s treated as an array by 9: its elements are added instead: 2Iterate: forEachThe arr.forEach method allows to run a function for every element of the array. The syntax: 3For instance, this shows each element of the array: 4And this code is more elaborate about their positions in the target array: 5The result of the function (if it returns any) is thrown away and ignored. Searching in arrayNow let’s cover methods that search in an array. indexOf/lastIndexOf and includesThe methods arr.indexOf and arr.includes have the similar syntax and do essentially the same as their string counterparts, but operate on items instead of characters:
Usually these methods are used with only one argument: the 1 to search. By default, the search is from the beginning.For instance: 6Please note that 9 uses the strict equality 0 for comparison. So, if we look for 1, it finds exactly 1 and not the zero.If we want to check if 1 exists in the array, and don’t need the index, then 4 is preferred.The method arr.lastIndexOf is the same as 9, but looks for from right to left. 7The A minor, but noteworthy feature of 6 is that it correctly handles 7, unlike 9: 8That’s because 6 was added to JavaScript much later and uses the more up to date comparison algorithm internally.find and findIndex/findLastIndexImagine we have an array of objects. How do we find an object with the specific condition? Here the arr.find(fn) method comes in handy. The syntax is: 9The function is called for elements of the array, one after another:
If it returns 7, the search is stopped, the 1 is returned. If nothing found, 07 is returned.For example, we have an array of users, each with the fields 08 and 09. Let’s find the one with 10: 0In real life arrays of objects is a common thing, so the 11 method is very useful.Note that in the example we provide to 11 the function 13 with one argument. That’s typical, other arguments of this function are rarely used.The arr.findIndex method has the same syntax, but returns the index where the element was found instead of the element itself. The value of 3 is returned if nothing is found.The arr.findLastIndex method is like 15, but searches from right to left, similar to 16.Here’s an example: 1filterThe 11 method looks for a single (first) element that makes the function return 7.If there may be many, we can use arr.filter(fn). The syntax is similar to 11, but 20 returns an array of all matching elements: 2For instance: 3Transform an arrayLet’s move on to methods that transform and reorder an array. mapThe arr.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: 4For instance, here we transform each element into its length: 5sort(fn)The call to arr.sort() sorts the array in place, changing its element order. It also returns the sorted array, but the returned value is usually ignored, as 5 itself is modified.For instance: 6Did you notice anything strange in the outcome? The order became 22. Incorrect. But why?The items are sorted as strings by default. Literally, all elements are converted to strings for comparisons. For strings, lexicographic ordering is applied and indeed 23.To use our own sorting order, we need to supply a function as the argument of 24.The function should compare two arbitrary values and return: 7For instance, to sort as numbers: 8Now it works as intended. Let’s step aside and think what’s happening. The 5 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 26 method implements a generic sorting algorithm. We don’t need to care how it internally works (an optimized quicksort or 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 27 which does the comparison.By the way, if we ever want to know which elements are compared – nothing prevents from alerting them: 9The algorithm may compare an element with multiple others in the process, but it tries to make as few comparisons as possible. A comparison function may return any number Actually, a comparison function is only required to return a positive number to say “greater” and a negative number to say “less”. That allows to write shorter functions: 0Arrow functions for the best Remember arrow functions? We can use them here for neater sorting: 1This works exactly the same as the longer version above. Use Remember strings comparison algorithm? It compares letters by their codes by default. For many alphabets, it’s better to use 29 method to correctly sort letters, such as 30.For example, let’s sort a few countries in German: 2reverseThe method arr.reverse reverses the order of elements in 5.For instance: 3It also returns the array 5 after the reversal.split and joinHere’s the situation from real life. We are writing a messaging app, and the person enters the comma-delimited list of receivers: 33. But for us an array of names would be much more comfortable than a single string. How to get it?The str.split(delim) method does exactly that. It splits the string into an array by the given delimiter 34.In the example below, we split by a comma followed by space: 4The 35 method has an optional second numeric argument – a limit on the array length. If it is provided, then the extra elements are ignored. In practice it is rarely used though: 5Split into letters The call to 36 with an empty 37 would split the string into an array of letters: 6The call arr.join(glue) does the reverse to 35. It creates a string of 5 items joined by 40 between them.For instance: 7reduce/reduceRightWhen we need to iterate over an array – we can use 41, 42 or 43.When we need to iterate and return the data for each element – we can use 44.The methods arr.reduce and arr.reduceRight also belong to that breed, but are a little bit more intricate. They are used to calculate a single value based on the array. The syntax is: 8The function is applied to all array elements one after another and “carries on” its result to the next call. Arguments:
As function is applied, the result of the previous function call is passed to the next one as the first argument. 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 51.Sounds complicated? The easiest way to grasp that is by example. Here we get a sum of an array in one line: 9The function passed to 51 uses only 2 arguments, that’s typically enough.Let’s see the details of what’s going on.
The calculation flow: Or in the form of a table, where each row represents a function call on the next array element: 53 57resultthe first call 4 9 9the second call 9 61 70the third call 70 70 73the fourth call 73 75 76the fifth call 76 78 79Here we can clearly see how the result of the previous call becomes the first argument of the next one. We also can omit the initial value: 0The result is the same. That’s because if there’s no initial, then 51 takes the first element of the array as the initial value and starts the iteration from the 2nd element.The calculation table is the same as above, minus the first row. But such use requires an extreme care. If the array is empty, then 51 call without initial value gives an error.Here’s an example: 1So it’s advised to always specify the initial value. The method arr.reduceRight does the same, but goes from right to left. Array.isArrayArrays do not form a separate language type. They are based on objects. So 82 does not help to distinguish a plain object from an array: 2…But arrays are used so often that there’s a special method for that: Array.isArray(value). It returns 7 if the 84 is an array, and 1 otherwise. 3Most methods support “thisArg”Almost all array methods that call functions – like 11, 20, 44, with a notable exception of 89, accept an optional additional parameter 90.That parameter is not explained in the sections above, because it’s rarely used. But for completeness we have to cover it. Here’s the full syntax of these methods: 4The value of 90 parameter becomes 92 for 93.For example, here we use a method of 94 object as a filter, and 90 passes the context: 5If in the example above we used 96, then 97 would be called as a standalone function, with 98, thus leading to an instant error.A call to 99 can be replaced with 00, that does the same. The latter is used more often, as it’s a bit easier to understand for most people.SummaryA cheat sheet of array methods:
Please note that methods 89, 41 and 1 modify the array itself.These methods are the most used ones, they cover 99% of use cases. But there are few others:
For the full list, see the manual. From the first sight it may seem that there are so many methods, quite difficult to remember. But actually that’s much easier. 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. Afterwards whenever you need to do something with an array, and you don’t know how – come here, look at the cheat sheet and find the right method. Examples will help you to write it correctly. Soon you’ll automatically remember the methods, without specific efforts from your side. |