Cheat Sheet Array Methods
Danny Engelman

Danny Engelman @dannyengelman

About: Online since 1990 Yes! I started with Gopher. I do modern Web Component Development with technologies supported by **all** WHATWG partners (Apple, Google, Microsoft & Mozilla)

Location:
Amsterdam, the Netherlands
Joined:
Oct 20, 2018

Cheat Sheet Array Methods

Publish Date: Jun 12 '21
6 0

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:

Comments 0 total

    Add comment