Skip to content

Instantly share code, notes, and snippets.

@rauschma
Last active March 18, 2024 09:49
Show Gist options
  • Save rauschma/6cdeb4af7586aa03baed2f925e0a084b to your computer and use it in GitHub Desktop.
Save rauschma/6cdeb4af7586aa03baed2f925e0a084b to your computer and use it in GitHub Desktop.

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  ['■','●']

Check out this quick reference for Array methods

My book “JavaScript for impatient programmers” contains a comprehensive quick reference:

  • Lists all Array methods (a few methods were omitted in the cheat sheet)
  • Brief explanations
  • Code examples
  • Method type signatures
@kart0111
Copy link

Thanks for wonderful document

@bdenham
Copy link

bdenham commented Jun 1, 2021

Well done! This might be then most instructive and efficient cheat sheet I’ve ever seen.

@Danny-Engelman
Copy link

cool! bit clearer with Colors/Emojis: https://array-methods.github.io/

@liorean
Copy link

liorean commented Jun 1, 2021

Missing the gotcha arguments that are the index and source arguments for the callback (using parseInt as a map callback is the classic gotcha), and perhaps the Array constructor and from method on the constructor.

@boeckMt
Copy link

boeckMt commented Jun 11, 2021

Also a really good sheet is this https://medium.com/@alvaro.saburido/set-theory-for-arrays-in-es6-eb2f20a61848

It shows things like Intersection, Difference, Symmetrical Difference and Union

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment