Cheat sheet: JavaScript Array methods
Deriving a new Array from an existing Array:
['โ ','โ','โฒ'].slice(1, 3) โผ ['โ','โฒ']
['โ ','โ','โ '].filter(x => x==='โ ') โผ ['โ ','โ ']
['โฒ','โ'].map(x => x+x) โผ ['โฒโฒ','โโ']
['โฒ','โ'].flatMap(x => [x,x]) โผ ['โฒ','โฒ','โ','โ']
Computing a summary of an Array:
['โ ','โ','โฒ'].some(x => x==='โ') โผ true
['โ ','โ','โฒ'].every(x => x==='โ') โผ false
['โ ','โ','โฒ'].join('-') โผ 'โ -โ-โฒ'
['โ ','โ'].reduce((result,x) => result+x, 'โฒ') โผ 'โฒโ โ'
['โ ','โ'].reduceRight((result,x) => result+x, 'โฒ') โผ 'โฒโโ '
Changing all of an Array (the input Array is modified and returned):
['โ ','โ','โฒ'].fill('โ') โผ ['โ','โ','โ']
['โ ','โ','โฒ'].reverse() โผ ['โฒ','โ','โ ']
['โ ','โ','โ '].sort() โผ ['โ ','โ ','โ']
Finding Array elements:
['โ ','โ','โ '].includes('โ ') โผ true
['โ ','โ','โ '].indexOf('โ ') โผ 0
['โ ','โ','โ '].lastIndexOf('โ ') โผ 2
['โ ','โ','โ '].find(x => x==='โ ') โผ 'โ '
['โ ','โ','โ '].findIndex(x => x==='โ ') โผ 0
Listing elements (spreading via ...
is needed because the methods return iterables):
[...['โ ','โ','โฒ'].keys()] โผ [0,1,2]
[...['โ ','โ','โฒ'].values()] โผ ['โ ','โ','โฒ']
[...['โ ','โ','โฒ'].entries()] โผ [[0,'โ '],[1,'โ'],[2,'โฒ']]
Adding or removing an element at either end of an Array:
arr=['โ ','โ']; arr.push('โฒ'); arr โผ ['โ ','โ','โฒ']
arr=['โ ','โ','โฒ']; arr.pop(); arr โผ ['โ ','โ']
arr=['โ ','โ']; arr.unshift('โฒ'); arr โผ ['โฒ','โ ','โ']
arr=['โฒ','โ ','โ']; arr.shift(); arr โผ ['โ ','โ']