|
| 1 | +# Array Methods in JavaScript |
| 2 | + |
| 3 | +Shift Lunch and Learn 7-26-19 |
| 4 | + |
| 5 | +## Overview |
| 6 | + |
| 7 | +- Why do native array methods matter? |
| 8 | +- Common array methods and what they do |
| 9 | +- Determine which array method to use in which situation |
| 10 | +- Practical (sort of) examples in React, etc |
| 11 | + |
| 12 | +## Why do array methods matter? |
| 13 | + |
| 14 | +- _Declarative_ vs _imperative_ |
| 15 | + - "Do this thing" vs "execute these steps" |
| 16 | +- Typically more succinct, more grok-able syntax |
| 17 | + |
| 18 | +```js |
| 19 | +function getResults(arr) { |
| 20 | + const results = []; |
| 21 | + |
| 22 | + for (let i = 0; i < arr.length; i++) { |
| 23 | + const element = arr[i]; |
| 24 | + |
| 25 | + if (someValidationFunction(element)) { |
| 26 | + results.push(element); |
| 27 | + } |
| 28 | + } |
| 29 | + |
| 30 | + return results; |
| 31 | +} |
| 32 | + |
| 33 | +// vs |
| 34 | + |
| 35 | +function getResults(arr) { |
| 36 | + return arr.filter(someValidationFunction); |
| 37 | +} |
| 38 | +``` |
| 39 | + |
| 40 | +- Chainable |
| 41 | +- Encourage reusability and composability |
| 42 | +- Standardized - handle edge cases, usable across environments |
| 43 | + |
| 44 | +## Common Array Methods |
| 45 | + |
| 46 | +- forEach |
| 47 | +- map |
| 48 | +- filter |
| 49 | +- reduce |
| 50 | +- some |
| 51 | +- every |
| 52 | +- find |
| 53 | +- includes |
| 54 | + |
| 55 | +Let's look at code! |
| 56 | + |
| 57 | +## When do I use which Array method? |
| 58 | + |
| 59 | +Use [this](https://sdras.github.io/array-explorer/) |
| 60 | + |
| 61 | +tl;dr |
| 62 | +|Method|When to Use| |
| 63 | +|------|-----------| |
| 64 | +|forEach|Run some code for every element, don't care about return value| |
| 65 | +|map|Run some code for every element, and track every return value separately| |
| 66 | +|filter|Only want part of the array that satisies a condition| |
| 67 | +|reduce|Run some code for every element, and "boil it down" to a single value at the end| |
| 68 | +|some|Is there at least one element that satisfies this condition?| |
| 69 | +|every|Do all elements satify this condition?| |
| 70 | +|find|Give me the first element that satisfies this condition| |
| 71 | +|inclues|Does this array contain this exact value?| |
| 72 | + |
| 73 | +## Quick React Demo |
| 74 | + |
| 75 | +Note: Extremely contrived and bad |
| 76 | + |
| 77 | +## Questions? |
| 78 | + |
| 79 | +## Additional Reading |
| 80 | + |
| 81 | +- https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/prototype |
| 82 | +- https://sdras.github.io/array-explorer/ |
| 83 | +- https://syntax.fm/show/043/20-javascript-array-and-object-methods-to-make-you-a-better-developer |
0 commit comments