Skip to content

Instantly share code, notes, and snippets.

@jessejputnam
Created August 16, 2022 12:57
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jessejputnam/28cfd0684cdf10524699cdf54252947a to your computer and use it in GitHub Desktop.
Save jessejputnam/28cfd0684cdf10524699cdf54252947a to your computer and use it in GitHub Desktop.
A cheatsheet for choosing JavaScript array methods

Choosing an array method

I want to...

Mutate the original array

  • Add to original:
arr.push
arr.unshift
  • Remove from original:
arr.pop
arr.shift
arr.splice

Return a new array

  • Computed from original
arr.map
  • Filtered using condition
arr.filter
  • Portion of original
arr.filter
  • Adding original to other
arr.concat
  • Flattening the original
arr.flat
arr.flatMap

Get an array index

  • Based on value
arr.indexOf
  • Based on test condition
arr.findIndex

Get an array element

  • Based on a text condition
arr.find

Know if the array includes...

  • Based on value
arr.includes
  • Based on test condition
arr.some
arr.every

Form array from a string

  • Based on separsator string
arr.join

Transform the array to a new value

  • Based on accumulator note: boils down array to single value of any type
arr.reduce

Loop over the array without returning a value

  • Based on callback note: does not create new array, just loops over it
arr.forEach
@djanatyn
Copy link

nice :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment