Last active
August 29, 2015 14:23
-
-
Save nuweb/a79e8b6fab3a2fbb4bdb to your computer and use it in GitHub Desktop.
Higher order functions in JavaScript
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
| var animals = [ | |
| { name: "Waffles", type: "dog", age: 12 }, | |
| { name: "Fluffy", type: "cat", age: 14 }, | |
| { name: "Spelunky", type: "dog", age: 4 }, | |
| { name: "Hank", type: "dog", age: 11 } | |
| ]; | |
| // filter dogs | |
| animals = animals.filter(function(animal) { | |
| return animal.type === "dog"; | |
| }); | |
| console.log(animals); | |
| // filter dogs whose age is greater than 4 | |
| animals = animals.filter(function(animal) { | |
| return animal.age > 4; | |
| }); | |
| console.log(animals); | |
| // get names of all dogs whose age is greater than 4 | |
| var names = animals.map(function(animal) { | |
| return animal.name; | |
| }); | |
| console.log(names); | |
| // get average age of animals | |
| var averageAge = animals.map(function(animal) { | |
| return animal.age; | |
| }).reduce(function(prev, curr) { | |
| return (prev+curr)/2; | |
| }); | |
| console.log(totalAge); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment