DEV Community

Cover image for Cheat Sheet Array Methods
Danny Engelman
Danny Engelman

Posted on

Cheat Sheet Array Methods

https://array-methods.github.io/

Credits: Axel Rauschmayer


Adding or removing an element at either end of an Array

(return value: item or new array length)

array before method return value array after
["🟦","🟑","πŸ”Ί"] .push("🟩") 4 ["🟦","🟑","πŸ”Ί","🟩"]
["🟦","🟑","πŸ”Ί"] .pop() "πŸ”Ί" ["🟦","🟑"]
["🟦","🟑","πŸ”Ί"] .unshift("🟩") 4 ["🟩","🟦","🟑","πŸ”Ί"]
["🟦","🟑","πŸ”Ί"] .shift() "🟦" ["🟑","πŸ”Ί"]
["🟦","🟑","πŸ”Ί"] .unshift(arr.pop()) 3 ["πŸ”Ί","🟦","🟑"]

https://array-methods.github.io/

Changing all of an Array

(the input Array is modified and returned)

array before method return 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) ["🟦",πŸ”Ί","πŸ”Ί","🟩" ]

https://array-methods.github.io/

Finding Array elements

array method return value
["🟦","🟑","πŸ”Ί"] .includes( "🟦" ) true
["🟦","🟑","πŸ”Ί"] .indexOf( "🟦" ) 0
["🟦","🟑","🟦"] .lastIndexOf( "🟦" ) 2
["🟦","🟑","πŸ”Ί"] .find( x => x==="🟦" ) "🟦"
["🟦","🟑","πŸ”Ί"] .findIndex( x => x==="🟦" ) 0

https://array-methods.github.io/

Creating a new Array from an existing Array

array before method (links to MDN) return value array after
["🟦","🟑","πŸ”Ί"] .slice(1, 2) ["🟑","πŸ”Ί"] ["🟦","🟑","πŸ”Ί"]
["🟦","🟑","πŸ”Ί"] .splice(1, 2) ["🟑","πŸ”Ί"] ["🟦"]
["🟦","🟑","🟦"] .filter( x => x==="🟦") ["🟦","🟦"] ["🟦","🟑","🟦"]
["🟦","🟑"] .map( x => x+x ) ["🟦🟦", "🟑🟑"] ["🟦","🟑"]
["🟦","🟑"] .map( x => [x+x] ) [["🟦🟦"], ["🟑🟑"]] ["🟦","🟑"]
["🟦","🟑"] .flatMap( x => [x,x] ) ["🟦","🟦","🟑","🟑"] ["🟦","🟑"]
["🟦","🟑","πŸ”Ί"] .concat( ["🟩","πŸ”΄"] ) ["🟦","🟑","πŸ”Ί","🟩","πŸ”΄"] ["🟦","🟑","πŸ”Ί"]

https://array-methods.github.io/

Computing a summary of an Array

array method return 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,"🟩") "πŸŸ©πŸ”ΊπŸŸ‘πŸŸ¦"

https://array-methods.github.io/

Listing elements

array method return 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) )
["","🟑","πŸ”ΊπŸ”Ί","🟩🟩🟩"]

More:

Oldest comments (0)