es6-array-methods.mdx
1 --- 2 title: ES6 high order array methods explained 3 date: 2020-07-29 4 description: A post where I try to explain ES6 array methods in a simplest way possible that I could think of. 5 tags: 6 - javascript 7 --- 8 9 # Introduction 10 11 ECMAScript 6 introduces some new array methods that is useful to loop through an array items. In this post, I'll try to explain how I understand some ES6 high order array methods like `map()`, `filter()`, `reduce()`, `forEach()`, etc. Hopefully you will understand more about these methods after reading this post. Let's get started. 12 13 # High Order Array Methods 14 15 ## Find 16 17 The first method is `Array.prototype.find()`. Just like the name suggest, it will find the item that you are looking for. It will return the item if the function returns true. Here's an example. 18 19 ```javascript 20 const users = [ 21 { 22 id: 1, 23 name: "John Doe", 24 admin: false, 25 }, 26 { 27 id: 2, 28 name: "Lukas Smith", 29 admin: true, 30 }, 31 { 32 id: 3, 33 name: "Erina Matsumoto", 34 admin: false, 35 }, 36 ]; 37 38 // will return {id: 1, name: "John Doe", admin: false} 39 users.find((user) => user.id === 1); 40 ``` 41 42 As you can see from the example, `Array.prototype.find()` returns the first item because we give it a condition to check if the item that is currently looping has the `id` of 1. 43 44 What if there are multiple matches? Well, `.find()` will only return the first match it found. So if you would type 45 46 ```javascript 47 user.find((user) => !user.admin); 48 ``` 49 50 It will return the first match which is `{id: 1, name: "John Doe", admin: false}`. If you want it to spit an array with matching condition, then you would use `.filter()` which we will talk about later. 51 52 `Array.prototype.find()` will return undefined if the given condition is not fulfilled (the item that you're looking for is not available). You can play around with this [here](https://repl.it/@elianiva/find-method). 53 54 ## Filter 55 56 Like I said earlier, if you want multiple results based off on your condition then you would use `Array.prototype.filter()`. Let's try it with the code below. 57 58 ```javascript 59 const cities = [ 60 { name: "Hiroshima", country: "Japan" }, 61 { name: "Sendai", country: "Japan" }, 62 { name: "London", country: "England" }, 63 { name: "Brighton", country: "England" }, 64 { name: "Jakarta", country: "Indonesia" }, 65 { name: "Bandung", country: "Indonesia" }, 66 ]; 67 68 // will return all cities in Japan 69 cities.filter((city) => city.country === "Japan"); 70 ``` 71 72 As you would expect, it returns an array with matching items. The code above will give us this result. 73 74 ```javascript 75 [ 76 { name: "Hiroshima", country: "Japan" }, 77 { name: "Sendai", country: "Japan" }, 78 ]; 79 ``` 80 81 You can play around with the code snippet above [here](https://repl.it/@elianiva/filter-method) 82 83 ## Some 84 85 What if you want to check if an array have some condition that you want? Well, `Array.prototype.some()` got you covered. This method checks if an array have _some_ condition that you want. Take a look at this example. 86 87 ```javascript 88 const items = [ 89 { name: "Phone", discount: true }, 90 { name: "Laptop", discount: false }, 91 { name: "Keyboard", discount: false }, 92 { name: "Mouse", discount: true }, 93 { name: "Monitor", discount: false }, 94 ]; 95 96 // will return true 97 items.some((item) => item.discount); 98 ``` 99 100 As you can see, it returns `true` because there are _some_ items that is currently in a discount. Go ahead and try to change them all to `false` on [repl.it](https://repl.it/@elianiva/some-method). 101 102 ## Every 103 104 OK great, now you can check whether or not an array has some items that match you requirements. There's also a method that will return `true` if _every_ one of them matches your condition. Check the code below. 105 106 ```javascript 107 const students = [ 108 { name: "Erika", passed: true }, 109 { name: "Himawari", passed: false }, 110 { name: "Irene", passed: false }, 111 { name: "Suzuka", passed: true }, 112 { name: "Riku", passed: true }, 113 ]; 114 115 // will return false 116 students.every((student) => student.passed); 117 ``` 118 119 It returns false because we need _every_ single one of the student passed. As always, you can play around with the code above [here](https://repl.it/@elianiva/every-method). 120 121 ## ForEach 122 123 `Array.prototype.forEach()` is useful if you want to just loop through an array and don't want to return anything. For example, if you just want to `console.log()` every item of an array. 124 125 ```javascript 126 const songs = ["Road of Resistance", "Pretender", "Megitsune", "Feel It Still", "Arkadia"]; 127 128 // will not return anything 129 songs.forEach((song) => console.log(song)); 130 ``` 131 132 You can play around with this method [here](https://repl.it/@elianiva/foreach-method). 133 134 ## Map 135 136 Similar to `.forEach()`, `Array.prototype.map()` will also loop through each item in an array but it will return a new array. Here's an example. 137 138 ```javascript 139 const numbers = [1, 2, 3, 4, 5]; 140 141 // will return multiplied value 142 numbers.map((num) => num * 2); 143 ``` 144 145 I use this method more often than `.forEach()` because most of the time I need to process that item and returns a new array with the result. You can play around with this [here](https://repl.it/@elianiva/map-method). 146 147 ## Reduce 148 149 Finally, `Array.prototype.reduce`. This method is quite hard for me to understand initially. It's sort of like merges the array. The first argument is the function handler that takes 2 arguments and the second argument is the initial value. The function's first argument called `accumulator` has the result of current iteration. The second argument called `currentValue` has the current item in an array. Let's look at the code and hope it will make more sense. 150 151 ```javascript 152 const numbers = [1, 1, 1, 1, 1]; 153 154 // will return 5 155 numbers.reduce((acc, curr) => acc + curr); 156 ``` 157 158 Let's make an analogy of that to make things simpler. Suppose you have a jar. That jar is the `accumulator`. The first time you have it, it's empty. Then you started to pick an item from a box. The box is an array and the item is the `currentValue`. You pick the item one by one, adding the total of the items in the jar (`accumulator`) with the item that you are picking (`currentValue`). Eventually, you will end up with 5 items. Same goes to the code above. 159 160 If you give it a second argument which is `initialValue`, then it will start from that value instead of 0. Just like if you have a jar filled with some items already. 161 162 ```javascript 163 const numbers = [1, 1, 1, 1, 1]; 164 165 // will return 10 166 numbers.reduce((acc, curr) => acc + curr, 5); 167 ``` 168 169 Reduce method is quite hard to understand at first, don't worry. Reduce deserves an article in itself, check out [this article](https://alligator.io/js/finally-understand-reduce/) to understand `reduce()` even more. 170 171 # References 172 173 There are so many references for these methods out there already. [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array) is one of the best reference out there if you want something more technical and detail. Also checkout [this tweet](https://twitter.com/profulsadangi/status/1288053880010334208) (and follow him too! He shared _a lot_ of useful stuff in a form of simple yet concise sketch). 174 175 # Conclusion 176 177 These methods that ES6 introduces is so useful. We no longer need to create a `for loop` that iterates through the whole array and then do something. Let me know what you think about this. See ya next time ツ