Skip to content

Instantly share code, notes, and snippets.

@ivan-ha
Last active June 26, 2017 03:36
Show Gist options
  • Select an option

  • Save ivan-ha/ba12b643b250ca6c0f472e273d2f40bc to your computer and use it in GitHub Desktop.

Select an option

Save ivan-ha/ba12b643b250ca6c0f472e273d2f40bc to your computer and use it in GitHub Desktop.
Simple note on map, filter and reduce on JS
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