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 | [βπΊβ,βπ¦β,βπ‘β] |
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) | [βπ¦β,πΊβ,βπΊβ,βπ©β ] |
Finding Array elements:
array | method | return value |
---|---|---|
[βπ¦β,βπ‘β,βπΊβ] | .includes( βπ¦β ) | true |
[βπ¦β,βπ‘β,βπΊβ] | .indexOf( βπ¦β ) | 0 |
[βπ¦β,βπ‘β,βπ¦β] | .lastIndexOf( βπ¦β ) | 2 |
[βπ¦β,βπ‘β,βπΊβ] | .find( x => x===βπ¦β ) | βπ¦β |
[βπ¦β,βπ‘β,βπΊβ] | .findIndex( x => x===βπ¦β ) | 0 |
Creating a new Array from an existing Array:
array before | method (links to MDN) | return value | array 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:
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,βπ©β) | βπ©πΊπ‘π¦β |
Listing elements:
array | method | return value (iterators) |
---|---|---|
[βπ¦β,βπ‘β,βπΊβ] | .keys() | [0,1,2] |
[βπ¦β,βπ‘β,βπΊβ] | .values() | [βπ¦β,βπ‘β,βπΊβ] |
[βπ¦β,βπ‘β,βπΊβ] | .entries() | [ [0,βπ¦β], [1,βπ‘β], [2,βπΊβ] ] |
spreading ... requiredbecause the above methods return iterators |
return value |
---|---|
[ β¦[βπ¦β,βπ‘β,βπΊβ,βπ©β].entries() ] Β Β Β Β .map( ([key,val]) => val.repeat(key) ) |
[ββ,βπ‘β,βπΊπΊβ,βπ©π©π©β] |