Common operations on JavaScript arrays: indexing, slicing, adding and removing items, and iterating.

Introduction

Accessing

list[1]                 // → b
list.indexOf(b)         // → 1
list.lastIndexOf(b)     // → 1
list.includes(b)        // → true

See: indexOf(), includes() (developer.mozilla.org)

Subsets

Immutable

list.slice(0,1)         // → [a        ]
list.slice(1)           // → [  b,c,d,e]
list.slice(1,2)         // → [  b      ]

Mutative

re = list.splice(1)     // re = [b,c,d,e]  list == [a]
re = list.splice(1,2)   // re = [b,c]      list == [a,d,e]

See: slice(), splice() (developer.mozilla.org)

Adding items

Immutable

list.concat([X,Y])      // → [_,_,_,_,_,X,Y]

Mutative

list.push(X)            // list == [_,_,_,_,_,X]
list.unshift(X)         // list == [X,_,_,_,_,_]
list.splice(2, 0, X)    // list == [_,_,X,_,_,_]

See: concat(), push(), unshift() (developer.mozilla.org)

Inserting

// after -- [_,_,REF,NEW,_,_]
list.splice(list.indexOf(REF) + 1, 0, NEW)
// before -- [_,_,NEW,REF,_,_]
list.splice(list.indexOf(REF), 0, NEW)

See: splice() (developer.mozilla.org)

Replace items

list.splice(2, 1, X)    // list == [a,b,X,d,e]

See: splice() (developer.mozilla.org)

Removing items

list.pop()              // → e    list == [a,b,c,d]
list.shift()            // → a    list == [b,c,d,e]
list.splice(2, 1)       // → [c]  list == [a,b,d,e]

See: pop(), shift(), splice() (developer.mozilla.org)

Iterating

list.forEach(n => ...)           // run fn for each item
list.filter(n => ...)            // → matching items
list.map(n => ...)               // → mapped items
list.find(n => ...)              // → first match (ES6)
list.findIndex(n => ...)         // → index of first match (ES6)
list.every(n => ...)             // → Boolean (ES5)
list.some(n => ...)              // → Boolean (ES5)
list.reduce((total, n) => ...)   // → single value

See: forEach(), map(), reduce() (developer.mozilla.org)

0 Comments for this cheatsheet. Write yours!