Skip to content

Instantly share code, notes, and snippets.

@akash-joshi
Created October 23, 2019 15:56
Show Gist options
  • Save akash-joshi/8ab89bc9cea1a6d3d83de6b88f04dfcc to your computer and use it in GitHub Desktop.
Save akash-joshi/8ab89bc9cea1a6d3d83de6b88f04dfcc to your computer and use it in GitHub Desktop.
// Map, Filter, Reduce, FlatMap cheatsheet 🤑
const myArray = [
{
name: "Akash",
age: 20
},
{
name: "Sagar",
age: 30
},
{
name: "Madhav",
age: 25
}
]
// 1. map -- n -> n w/ operations
const mappedArray = myArray.map((element,index) => element.age * 2 )
console.log(mappedArray)
// 2. filter -- n -> <=n w/o operations
const filterFunc = element => element.age >= 25
const filteredArray = myArray.filter(filterFunc)
console.log(filteredArray)
// 3. reduce -- n -> 1 w/ operations
const reducedOutput = myArray.reduce((accumulator, element) => accumulator + element.age, 0);
console.log(reducedOutput)
// 4. flatMap -- n -> <=n w/ operations >= node 11.0.0
const a = [1,2,3,4]
const squareEvenArray = a.flatMap(element => element % 2 == 0 ? element * element : []);
console.log(squareEvenArray)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment