Skip to content

Instantly share code, notes, and snippets.

@danny-andrews
Forked from rauschma/array-cheat-sheet.md
Last active August 25, 2021 21:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save danny-andrews/c1b7abb22dfc2f7270dfa147107c4b0b to your computer and use it in GitHub Desktop.
Save danny-andrews/c1b7abb22dfc2f7270dfa147107c4b0b to your computer and use it in GitHub Desktop.

Cheat sheet: JavaScript Array methods

Finding Array elements:

['■', '●', '■'].includes('■')            true
['■', '●', '■'].indexOf('■')             0
['■', '●', '■'].lastIndexOf('■')         2
['■', '●', '■'].find(x => x==='■')       ''
['■', '●', '■'].findIndex(x => x==='■')  0

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, '▲')   '▲●■'

Adding or removing an element from Array:

// End
arr=['■','●'];     arr.push('▲');    arr  ['■', '●', '▲']
arr=['■','●','▲']; arr.pop();        arr  ['■', '●']

// Beginning
arr=['■','●'];     arr.unshift('▲'); arr  ['▲', '■', '●']
arr=['▲','■','●']; arr.shift();      arr  ['■', '●']

// Middle
arr=['▲','■','●']; arr.splice(1, 1); arr  ['▲', '●']

Modifying an Array (the input Array is modified and returned):

['■', '●', '▲'].fill('●')  ['●', '●', '●']
['■', '●', '▲'].reverse()  ['▲', '●', '■']
['■', '●', '■'].sort()     ['■', '■', '●']

Deriving a new Array from an existing Array:

['■', '●', '▲'].slice(1, 3)              ['●', '▲']
['■', '●', '■'].filter(x => x === '■')   ['■', '■']
['▲', '●'].map(x => x + x)               ['▲▲','●●']
['▲', '●'].flatMap(x => [x, x])          ['▲', '▲', '●', '●']
['■'].concat(['●', '▲'])                 ['■', '●', '▲']

Creating an array of length N:

[...Array(4).keys()]  [0, 1, 2, 3]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment