Skip to content

Instantly share code, notes, and snippets.

@ixzy24
Forked from nuweb/filter-map-reduce.js
Last active August 29, 2015 14:23
Show Gist options
  • Save ixzy24/af78e24567e977c5a572 to your computer and use it in GitHub Desktop.
Save ixzy24/af78e24567e977c5a572 to your computer and use it in GitHub Desktop.
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 whose age is greater than 4
var totalAge = 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