Skip to content

Instantly share code, notes, and snippets.

@OleksiyRudenko
Last active April 10, 2019 11:50
Show Gist options
  • Save OleksiyRudenko/c755ae87a36b0864e83ec7af90968c01 to your computer and use it in GitHub Desktop.
Save OleksiyRudenko/c755ae87a36b0864e83ec7af90968c01 to your computer and use it in GitHub Desktop.
ES6+ cheatsheet
// initial array
const a = [A,B,C];
// [ABC] is a short-hand notation for [A,B,C]
Array method | arguments | ES6 shorthand | returns | a if mutated
-----------------------------------------------------------------------------------
--- Adding elements
.push D,E .length (5) [ABCDE]
.push [DE] .length (4) [ABC[DE]]
[...a, D, E] [ABCDE]
[...a, [DE]] [ABC[DE]]
.concat [DE] [...a, ...[DE]] [ABCDE]
.concat ...[DE] [...a, ...[DE]] [ABCDE]
.concat D,E [...a, ...[DE]] [ABCDE]
.unshift D,E [D,E, ...a] [DEABC]
--- Extracting elements
[head, ...tail]=a head=A, tail=[B,C]
.pop C [AB]
.shift A [BC]
.slice [ABC]
.slice 1 [BC]
.slice 1,2 a[1] [B]
.splice [] [ABC]
.splice 1 [BC] [A]
.splice 1,1 [B] [AC]
.splice 1,1,D,E [B] [ADEC]
.splice 1,1,[DE] [B] [A[DE]C]
.splice 1,0,D,E [] [ADEBC]
NB! delete doesn't affect .length
===================================================================================
Looping
Array method | callback | callback | optional | method returns
| args | returns | arg |
-----------------------------------------------------------------------------------
.forEach el[,idx[,a]] undefined this undefined
.find el[,idx[,a]] false|true this first matching element | undefined
.findIndex el[,idx[,a]] false|true this first matching element index | -1
for const idx in a
for const el of a
.map el[,idx[,a]] any this [transformed elements]
.filter el[,idx[,a]] false|true this [matching elements]
.every el[,idx[,a]] false|true this true if every cb invocation returns true
.some el[,idx[,a]] false|true this true if at least one cb invocation returns true
.reduce acc,el[,idx[,a]] updated acc initial acc reduced value // by default acc initialized from a[0]
.reduceRight acc,el[,idx[,a]] updated acc initial acc reduced value // by default acc initialized from
Notes on reducers:
1. If no initial acc value specified then acc gets initialized (equals to) on first iteration from
a[0] (.reduce) or a[a.length-1] (.reduceRight).
2. Pay special attention to arrays of objects when defaulting acc to an element of source array.
[{a:'A'},{a:'B'},{a:'C'}].reduce((acc,el) => acc.a + el.a) // undefinedC
[{a:'A'},{a:'B'},{a:'C'}].reduce((acc,el) => ({a:acc.a + el.a})) // {a:'ABC'}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment