Created
May 13, 2019 10:45
-
-
Save jeandcr/2234e59174a7ed1a7c2600dfc139144a to your computer and use it in GitHub Desktop.
JS Loops using map, filter, reduce and find
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // | |
| // Finding a single element in the array | |
| // | |
| // filter returns an array with less items than the original array | |
| const performSomething = (item) => { | |
| return item | |
| } | |
| const items = ['a', 'b', 'c'] | |
| items.forEach((item) => { | |
| performSomething(item) | |
| }) | |
| // declarative approach | |
| // ES6 | |
| const b = items.find((item) => item.name === 'b') |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // | |
| // Execute something on every element with map | |
| // | |
| // map returns an array with the same length | |
| // With a loop | |
| const performSomething = (item) => { | |
| return item | |
| } | |
| const items = ['a', 'b', 'c'] | |
| items.forEach((item) => { | |
| performSomething(item) | |
| }) | |
| // declarative appproach | |
| const items = ['a', 'b', 'c'] | |
| const newArray = items.map((item) => performSomething(item)) | |
| // because we only have one function defined in the callback, | |
| // we can simplify this even more to the following | |
| const items = ['a', 'b', 'c'] | |
| const newArray = items.map(performSomething) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // | |
| // Iterate over an array to count a property of each item | |
| // | |
| // reduce returns a single value (or object) | |
| const items = [ | |
| { name: 'a', content: { value: 1 }}, | |
| { name: 'b', content: { value: 2 }}, | |
| { name: 'c', content: { value: 3 }} | |
| ] | |
| let count = 0 | |
| for (const item of items) { | |
| count += item.content.value | |
| } | |
| //declarative approach | |
| const count = items.reduce((result, { content: { value } }) => result + value, 0) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment