Skip to content

Instantly share code, notes, and snippets.

@jeandcr
Created May 13, 2019 10:45
Show Gist options
  • Select an option

  • Save jeandcr/2234e59174a7ed1a7c2600dfc139144a to your computer and use it in GitHub Desktop.

Select an option

Save jeandcr/2234e59174a7ed1a7c2600dfc139144a to your computer and use it in GitHub Desktop.
JS Loops using map, filter, reduce and find
//
// Finding a single element in the array
//
// filter returns an array with less items than the original array
const performSomething = (item) => {
return item
}
const items = ['a', 'b', 'c']
items.forEach((item) => {
performSomething(item)
})
// declarative approach
// ES6
const b = items.find((item) => item.name === 'b')
//
// Execute something on every element with map
//
// map returns an array with the same length
// With a loop
const performSomething = (item) => {
return item
}
const items = ['a', 'b', 'c']
items.forEach((item) => {
performSomething(item)
})
// declarative appproach
const items = ['a', 'b', 'c']
const newArray = items.map((item) => performSomething(item))
// because we only have one function defined in the callback,
// we can simplify this even more to the following
const items = ['a', 'b', 'c']
const newArray = items.map(performSomething)
//
// Iterate over an array to count a property of each item
//
// reduce returns a single value (or object)
const items = [
{ name: 'a', content: { value: 1 }},
{ name: 'b', content: { value: 2 }},
{ name: 'c', content: { value: 3 }}
]
let count = 0
for (const item of items) {
count += item.content.value
}
//declarative approach
const count = items.reduce((result, { content: { value } }) => result + value, 0)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment