Last active
June 26, 2017 03:36
-
-
Save ivan-ha/ba12b643b250ca6c0f472e273d2f40bc to your computer and use it in GitHub Desktop.
Simple note on map, filter and reduce on JS
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
| const animals = [ | |
| { | |
| "name": "cat", | |
| "size": "small", | |
| "weight": 5 | |
| }, | |
| { | |
| "name": "dog", | |
| "size": "small", | |
| "weight": 10 | |
| }, | |
| { | |
| "name": "lion", | |
| "size": "medium", | |
| "weight": 150 | |
| }, | |
| { | |
| "name": "elephant", | |
| "size": "big", | |
| "weight": 5000 | |
| } | |
| ]; | |
| // Map - do same operation on each array element, return an array of same size | |
| animals.map(animal => animal.name); | |
| // ["cat", "dog", "lion", "elephant"] | |
| // Filter - return array that matching certain criteria | |
| animals.filter(animal => animal.size === "small"); | |
| /* | |
| [ | |
| { | |
| "name": "cat", | |
| "size": "small", | |
| "weight": 5 | |
| }, | |
| { | |
| "name": "dog", | |
| "size": "small", | |
| "weight": 10 | |
| } | |
| ] | |
| */ | |
| // Reduce - use the values in an array and return something completely new | |
| animals.reduce((weight, animal) => {return weight += animal.weight}, 0); | |
| // 5165 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment