Danny Engelman

Posted on

# Cheat Sheet Array Methods

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

### 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
["π¦","π‘","πΊ"] .pop() "πΊ" ["π¦","π‘"]
["π¦","π‘","πΊ"] .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
Array(4) .fill("πΊ") ["πΊ","πΊ","πΊ","πΊ"]
Array(4) .fill("πΊ")
.map( (val,idx) => idx )
[ 0, 1, 2, 3 ]
["c","a","d","b"] .sort() ["a","b","c","d"]

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] ) ["π¦","π¦","π‘","π‘"] ["π¦","π‘"]

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

### Computing a summary of an Array

array method return value
["π¦","π‘","πΊ"] .some( x => x==="π‘" ) true
["π¦","π‘","πΊ"] .every( x => x==="π‘" ) false
[ 2, 3, 4 ] .reduce( (result,x) => result+x, 10 ) 19 10+2+3+4

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