|
| 1 | +# Simple Array Methods |
| 2 | + |
| 3 | +Methods are functions attached to objects and since arrays have methods themselves, arrays are basically objects as well. |
| 4 | + |
| 5 | +We use this built-in methods for manipulating arrays and handling several operations. |
| 6 | + |
| 7 | +## Slice Method (Array.slice(start index, end index)) |
| 8 | + |
| 9 | +Similar to the slice method on strings, we use this method to extract parts of an array without changing the main array. |
| 10 | + |
| 11 | +We simply do this by using the `.slice()` keyword and pass in the start and end index we want to slice from. |
| 12 | + |
| 13 | +```js |
| 14 | +const arr = ['a', 'b', 'c', 'd', 'e']; |
| 15 | +arr.slice(2); // Result will be ['c', 'd', 'e'] |
| 16 | +``` |
| 17 | + |
| 18 | +This will slice the first [0], second [1] elements and start extracting at position [2] of the array, as defined in the method. |
| 19 | + |
| 20 | +We can also define start and end positions of this method. |
| 21 | + |
| 22 | +```js |
| 23 | +arr.slice(2, 4); // ['c', 'd' ] |
| 24 | +``` |
| 25 | + |
| 26 | +What this will basically do is return [2] and [3]. And remember the length of the output array will be the end position minus the start position. |
| 27 | + |
| 28 | +So `4 - 2 = 2` and so the result are two elements `['c', d]` |
| 29 | + |
| 30 | +> **Note** |
| 31 | +> It does not mutate the original array but rather creates a copy or clone from the original array with the extracted parts |
| 32 | +
|
| 33 | +We can also use negative numbers. For example |
| 34 | + |
| 35 | +```js |
| 36 | +arr.slice(-2); // This will give us the last two elements of the array. |
| 37 | +``` |
| 38 | + |
| 39 | +Finally we can use the slice method to create a shallow copy of the array which is similar to how we used the spread operator to create a shallow copy of the array. |
| 40 | + |
| 41 | +```js |
| 42 | +arr.slice(); // ['a', 'b', 'c', 'd', 'e'] |
| 43 | +[...arr]; // ['a', 'b', 'c', 'd', 'e'] |
| 44 | +``` |
| 45 | + |
| 46 | +You can use either methods to create a shallow copy of an array, but you only use the `.slice()` method when we want to chain multiple array methods. |
| 47 | + |
| 48 | +## Splice Method (Array.splice(start index, delete count)) |
| 49 | + |
| 50 | +This works the same way with the slice method, except it mutates the original array. |
| 51 | + |
| 52 | +```js |
| 53 | +arr.splice(2); // ['c', 'd', 'e'] |
| 54 | +console.log(arr); // Remaining elements after splice method ['a', 'b'] |
| 55 | +arr.splice(-1); |
| 56 | +console.log(arr); // returns last element only ['e'] |
| 57 | +``` |
| 58 | + |
| 59 | +In real-world scenario, we don't usually have need for the remaning elements in an array, a good use case of the splice method is removing the last element from an array. |
| 60 | + |
| 61 | +```js |
| 62 | +arr.splice(-1); // ['a', 'b' 'c', 'd'] |
| 63 | +console.log(arr); |
| 64 | +``` |
| 65 | + |
| 66 | +The splice method also takes in a second argument. Except instead of selecting the last element of the array, it is used to specify the number of elements we want to delete starting from the first index. I.e `deleteCount` |
| 67 | + |
| 68 | +```js |
| 69 | +arr.splice(1, 2); // ['b', 'c'] Starts from index [1] and select only 2 elements |
| 70 | +``` |
| 71 | + |
| 72 | +## Reverse Array.reverse(Array) |
| 73 | + |
| 74 | +The reverse array method is used to reverse the order of an array. |
| 75 | + |
| 76 | +```js |
| 77 | +arr = ['a', 'b', 'c', 'd', 'e']; |
| 78 | +const arr2 = ['j', 'i', 'h', 'g', 'f']; |
| 79 | +console.log(arr2.reverse()); // ['f', 'g', 'h', 'i', 'j'] |
| 80 | +console.log(arr2); // ['f', 'g', 'h', 'i', 'j'] |
| 81 | +``` |
| 82 | + |
| 83 | +The reverse method also mutates the array. Using this method will reverse the original array. |
| 84 | + |
| 85 | +## Concat Array.concat(object) |
| 86 | + |
| 87 | +This method is used to concat arrays together. |
| 88 | + |
| 89 | +```js |
| 90 | +const joinedArr = arr.concat(arr2); |
| 91 | +console.log(joinedArr); // ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']; |
| 92 | +``` |
| 93 | + |
| 94 | +The concat method of course does not mutate the original array. |
| 95 | + |
| 96 | +## Join (Array.prototype.join(seperator)) |
| 97 | + |
| 98 | +The join method as we've seen is used to concatenate all the elements of an array using a specified seperator string |
| 99 | + |
| 100 | +# Looping Arrays forEach() |
| 101 | + |
| 102 | +Previosuly we used the `for of` loop to loop between arrays, the `forEach` method also allows us to loop between array but in a more different way. |
| 103 | + |
| 104 | +### Looping with for of loop |
| 105 | + |
| 106 | +```js |
| 107 | +const movements = [200, 450, -400, 3000, -650, -130, 70, 1300]; |
| 108 | + |
| 109 | +for (const transactions of movements) { |
| 110 | + transactions < 1 |
| 111 | + ? console.log(`You withdrew ${Math.abs(transactions)}`) |
| 112 | + : console.log(`You deposited ${transactions}`); |
| 113 | +} |
| 114 | +``` |
| 115 | + |
| 116 | +### Looping with forEach |
| 117 | + |
| 118 | +```js |
| 119 | +const movements = [200, 450, -400, 3000, -650, -130, 70, 1300]; |
| 120 | + |
| 121 | +movements.forEach(function (transactions) { |
| 122 | + transactions < 1 |
| 123 | + ? console.log(`You withdrew ${Math.abs(transactions)}`) |
| 124 | + : console.log(`You deposited ${transactions}`); |
| 125 | +}); |
| 126 | +``` |
| 127 | + |
| 128 | +The callback function executes at every iteration, so: |
| 129 | + |
| 130 | +```js |
| 131 | +0: function(200) |
| 132 | +1: function(450) |
| 133 | +2: function(-400) |
| 134 | +// ... |
| 135 | +``` |
| 136 | + |
| 137 | +The `forEach` method is a higher order function that takes in a callback function that is executed at it iteration of looping through an array. |
| 138 | + |
| 139 | +As the `forEach` method calls the callback function in each iteration, it will pass in the current element of the array as an argument passed into the function. |
| 140 | + |
| 141 | +The `forEach` method also uses arrow functions. |
| 142 | + |
| 143 | +```js |
| 144 | +movements.forEach(transactions => |
| 145 | + transactions < 1 |
| 146 | + ? console.log(`You withdrew ${Math.abs(transactions)}`) |
| 147 | + : console.log(`You deposited ${transactions}`) |
| 148 | +); |
| 149 | +``` |
| 150 | + |
| 151 | +### Accessing Index in forEach |
| 152 | + |
| 153 | +Previously we looked at how to access indexes of arrays with the `for of` loop: |
| 154 | + |
| 155 | +```js |
| 156 | +for (const [i, transactions] of movements.entries) { |
| 157 | +} |
| 158 | +``` |
| 159 | + |
| 160 | +The `forEach` method also does this and even returns the element, the index, and even the entire array we're looping. |
| 161 | +
|
| 162 | +```js |
| 163 | +movements.forEach(transcations, i, arr) { |
| 164 | + transact < 1 |
| 165 | + ? console.log(`Transaction ${i}: You withdrew ${Math.abs(transact)}`, arr) |
| 166 | + : console.log(`Transaction ${i}: You deposited ${transact}`, arr); |
| 167 | +} |
| 168 | +``` |
| 169 | +
|
| 170 | +The names does not matter but the order has to be `element, index, array` |
| 171 | +
|
| 172 | +> **Note** |
| 173 | +> The order of values is different in the `for of` loop and `forEach` method. |
| 174 | +
|
| 175 | +`for of (index, element)` |
| 176 | +`forEach (element, index, array)` |
| 177 | +
|
| 178 | +## forEach or for of Loop? |
| 179 | +
|
| 180 | +- The forEach method does not have the `continue` and `break` keywords, so use the for of loop if you absolutely want to break or continue a looping operation. |
0 commit comments