Skip to content

Instantly share code, notes, and snippets.

@mrmartineau
Forked from ggauravr/array_iteration_thoughts.md
Last active November 22, 2022 15:10
Show Gist options
  • Select an option

  • Save mrmartineau/9e39954c0afe02f53b4c0c7814bc601b to your computer and use it in GitHub Desktop.

Select an option

Save mrmartineau/9e39954c0afe02f53b4c0c7814bc601b to your computer and use it in GitHub Desktop.
Array iteration methods summarized

While attempting to explain JavaScript's reduce method on arrays, conceptually, I came up with the following - hopefully it's helpful; happy to tweak it if anyone has suggestions.

method name callback is a predicate? what does the callback answer? what arguments does the callback get? what is the final return value?
forEach no here’s an item. do something nutty with it, i don't care what. item, index, list nothing - in other words, undefined
map no here’s an item. what should i replace it with? item, index, list list of new items
filter yes should i keep this item? item, index, list list of kept items
reduce no here’s the result from the previous iteration. what should i pass to the next iteration? result, item, index, list result of last iteration
reduceRight no (same as reduce, but in reversed order: last-to-first)
some yes does this item meet your criteria? item, index, list true after the first item that meets your criteria, else false
every yes does this item meet your criteria? item, index, list false after the first item that failed to meet your criteria, else true
find yes is this item what you’re looking for? item, index, list the item you’re looking for, or undefined
findIndex yes is this item what you’re looking for? item, index, list the index of the item you’re looking for, or -1
  • note: a "predicate" is a function that returns a boolean - ie, true or false. (technically it will accept any truthy or falsy value, and effectively coerce it to a boolean for you)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment