Skip to content

Folders and files

NameName
Last commit message
Last commit date

Latest commit

History

45 Commits

Repository files navigation

Cheat sheet: JavaScript Array methods

Credits: Axel Rauschmayer

Adding or removing an element at either end of an Array: (return value: item or new array length)

array beforemethodreturn valuearray after
["🟦","🟡","🔺"].push("🟩")4["🟦","🟡","🔺","🟩"]
["🟦","🟡","🔺"].pop()"🔺"["🟦","🟡"]
["🟦","🟡","🔺"].unshift("🟩")4["🟩","🟦","🟡","🔺"]
["🟦","🟡","🔺"].shift()"🟦"["🟡","🔺"]
["🟦","🟡","🔺"].unshift(arr.pop())3["🔺","🟦","🟡"]

Changing all of an Array (the input Array is modified and returned):

array beforemethodreturn value
["🟦","🟡","🔺","🟩"].fill("🟡")["🟡","🟡","🟡","🟡"]
Array(4).fill("🔺")["🔺","🔺","🔺","🔺"]
Array(4).fill("🔺").map( (val,idx) => idx )[ 0, 1, 2, 3 ]
["🟦","🟡","🔺","🟩"].reverse()["🟩","🔺","🟡","🟦"]
["c","a","d","b"].sort()["a","b","c","d"]
["🟦","🟡","🔺","🟩"].sort()["🔺","🟡","🟦","🟩"]
["🟦","🟡","🔺","🟩" ].copyWithin(1,2,3)["🟦",🔺","🔺","🟩" ]

Finding Array elements:

arraymethodreturn value
["🟦","🟡","🔺"].includes( "🟦" )true
["🟦","🟡","🔺"].indexOf( "🟦" )0
["🟦","🟡","🟦"].lastIndexOf( "🟦" )2
["🟦","🟡","🔺"].find( x => x==="🟦" )"🟦"
["🟦","🟡","🔺"].findIndex( x => x==="🟦" )0

Creating a new Array from an existing Array:

array beforemethod (links to MDN)return valuearray after
["🟦","🟡","🔺"].slice(1, 3)["🟡","🔺"]["🟦","🟡","🔺"]
["🟦","🟡","🔺"].splice(1, 2)["🟡","🔺"]["🟦"]
["🟦","🟡","🟦"].filter( x => x==="🟦")["🟦","🟦"]["🟦","🟡","🟦"]
["🟦","🟡"].map( x => x+x )["🟦🟦", "🟡🟡"]["🟦","🟡"]
["🟦","🟡"].map( x => [x+x] )[["🟦🟦"], ["🟡🟡"]]["🟦","🟡"]
["🟦","🟡"].flatMap( x => [x,x] )["🟦","🟦","🟡","🟡"]["🟦","🟡"]
["🟦","🟡","🔺"].concat( ["🟩","🔴"] )["🟦","🟡","🔺","🟩","🔴"]["🟦","🟡","🔺"]

Computing a summary of an Array:

arraymethodreturn value
["🟦","🟡","🔺"].some( x => x==="🟡" )true
["🟦","🟡","🔺"].every( x => x==="🟡" )false
["🟦","🟡","🔺"].join( "🟩" )"🟦🟩🟡🟩🔺"
[ 2, 3, 4 ].reduce( (result,x) => result+x, 10 )19 10+2+3+4
["🟦","🟡","🔺"].reduce( (result,x) => result+x,"🟩")"🟩🟦🟡🔺"
["🟦","🟡","🔺"].reduceRight( (result,x) => result+x,"🟩")"🟩🔺🟡🟦"

Listing elements:

arraymethodreturn value (iterators)
["🟦","🟡","🔺"].keys()[0,1,2]
["🟦","🟡","🔺"].values()["🟦","🟡","🔺"]
["🟦","🟡","🔺"].entries()[ [0,"🟦"], [1,"🟡"], [2,"🔺"] ]
spreading ... required
because the above methods return iterators
return value
[ ...["🟦","🟡","🔺","🟩"].entries() ]
.map( ([key,val]) => val.repeat(key) )
["","🟡","🔺🔺","🟩🟩🟩"]

About

Examples Array Methods

Topics

Resources

Stars

7 stars

Watchers

1 watching

Forks

Contributors