Skip to content

Instantly share code, notes, and snippets.

@nuweb
Last active August 29, 2015 14:23
Show Gist options
  • Select an option

  • Save nuweb/a79e8b6fab3a2fbb4bdb to your computer and use it in GitHub Desktop.

Select an option

Save nuweb/a79e8b6fab3a2fbb4bdb to your computer and use it in GitHub Desktop.
Higher order functions in JavaScript
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