clubmate.fi

A good[ish] website

Web development blog, loads of UI and JavaScript topics

JavaScript array method cheat sheet

Filed under: Cheat sheets— Tagged with: iteration, sorting

A searchable quick reference of all JavaScript array methods, with simple examples.

Adding
CommandDescription
.push()Add anything to the end of an array.
let a = []
let b = {}
a.push(b)
console.log(a[0] === b) // true
.push()Add more than one item at a time.
let x = ['a']
x.push('b', 'c')
console.log(x) // ['a', 'b', 'c']
.unshift()Add to the beginning of array and returns the new length of the array.
let x = ['c', 'd']
x.unshift('a', 'b') // 4
console.log(x) // ['a', 'b', 'c', 'd']
.splice()Add element to an arbitrary location (second param 0).
let a = [1, 2, 3, 4]
a.splice(2, 0, 'foo')
console.log(a) // [1, 2, "foo", 3, 4]
Reorganizing
CommandDescription
.copyWithin()Copy part of an array to another location within the same array.
let a = ['a', 'b', 'c', 'd', 'e']
// target, start, end
array1.copyWithin(0, 3, 4)
console.log(a) // ["d", "b", "c", "d", "e"]
.slice()Returns a portion of an array selected with the start and end parameters.
let a = ['ant', 'bison', 'camel', 'duck', 'elephant']
console.log(animals.slice(2)) // ["camel", "duck", "elephant"]
console.log(animals.slice(2, 4)) // ["camel", "duck"]
.splice()Replace an arbitrary element in array (second param 1).
let a = [1, 2, 3, 4]
a.splice(2, 1, 'foo')
console.log(a) // [1, 2, "foo", 4]
Combining
CommandDescription
.concat()Create a new array from two arrays.
let x = ['a', 'b', 'c']
let y = ['d', 'e', 'f']
let z = x.concat(y)
console.log(z) // ['a', 'b', 'c', 'd', 'e', 'f']
...Not a method, but create a new array from two arrays by spreading them.
let x = ['a', 'b']
let y = ['c', 'd']
let z = [...x, ...y]
console.log(z) // ['a', 'b', 'c', 'd']
Removing
CommandDescription
.pop()Removes the last element from array and returns it. Changes the length of the array.
let a = ['a', 'b', 'c']
console.log(a.pop()) // c
console.log(a) // ["a", "b"]
.shift()Like pop but removes the first element from array and returns it. Also changes the length of the array.
let a = ['a', 'b', 'c']
console.log(a.shift()) // a
console.log(a) // ["b", "c"]
.splice()Remove elements from the middle of an array. Param 1: index to start removing. Param 2: index to stop removing.
let a = ['a', 'b', 'c', 'd', 'e']
a.splice(1, 3)
console.log(a) // ["a", "e"]
Filtering/Searching
CommandDescription
.filter()Keeps the items in the array that pass the test provided by the callback function.
let a = ['foo', 'bar', 'fooz']
let b = a.filter(v => v.startsWith('foo'))
console.log(b) // ['foo', 'fooz']
.find()Finds the first item in an array that matches.
let a = [5, 12, 8, 130, 44]
let b = a.find(v => v > 10)
console.log(b) // 12
.findIndex()Like find but instead of returning the item, it returns the index.
let a = [5, 12, 8, 130, 44]
let b = a.findIndex(v => v > 13)
console.log(b) // 3
.indexOf()Finds the first index of an element. Returns -1 if not found.
let a = ['foo', 'bar', 'baz']
console.log(a.indexOf('baz')) // 2
console.log(a.indexOf('quix')) // -1
.lastIndexOf()Like indexOf, but finds the last index of an element. Returns -1 if not found.
let a = ['foo', 'bar', 'baz', 'foo']
console.log(a.lastIndexOf('foo')) // 3
console.log(a.lastIndexOf('quix')) // -1
Sorting
CommandDescription
.sort()Sort alphabetically.
let a = ['d', 'j', 'a', 'b', 'c', 'g']
a.sort()
console.log(a) // ["a", "b", "c", "d", "g", "j"]
.sort()Sort in reversed alphabetical order.
let a = ['d', 'j', 'a', 'b', 'c', 'g']
a.sort().reverse()
console.log(a) // [ "j", "g", "d", "c", "b", "a"]
.sort()Sort numerically.
let a = [5, 10, 7, 1, 3, 2]
a.sort((a, b) => a - b)
console.log(a) // [ 1, 2, 3, 5, 7, 10]
.sort()Descending numerical sort (flip the `a` anb `b` around).
let a = [5, 10, 7, 1, 3, 2]
a.sort((a, b) => b - a)
console.log(a) // [10, 7, 5 ,3, 2, 1]
Loop structures
CommandDescription
.map()Maps an array to another array by executing a callback function on each element.
let a = [1, 2, 3, 4]
let b = a.map(v => v * 2)
console.log(b) // 2, 4, 6, 8
.flatMap()Same as map but it flattens the array, same as: [[]].map(v => v).flat().
let a = [1, 2, 3, 4]
let b = a.flatMap(v => [v * 2])
console.log() // 2, 4, 6, 8
.forEach()Executes a function for every element in array, does not return anything.
let a = [1, 2]
a.forEach(x => console.log(x))
// 1
// 2
.reduce()Executes a user-supplied “reducer” callback function on each element of the array, in order, passing in the return value from the calculation on the preceding element.
let a = [1, 2, 3, 4]
let b = a.reduce((acc, v) => acc + v)
// Basically: 1 + 2 + 3 + 4
console.log(b) // 10
.reduce()Return object from an array method.
let a = [1, 2, 3, 4]
let b = a.reduce((acc, v) => ({ [v]: v, ...acc }), {})
console.log(b) // {"1": 1,"2": 2,"3": 3,"4": 4}
.reduceRight()Like reduce but reads the array from right to left.
let a = [1, 2, 3, 4]
let b = a.reduce((acc, v) => acc + v)
// Basically: 1 + 2 + 3 + 4
console.log(b) // 10
Booleans
CommandDescription
.every()Tests if every item in the array passes the test.
let isBelow = v => v < 40
let a = [1, 30, 39, 29, 10, 13]
console.log(a.every(isBelow)) // true
.some()Tests if some items in the array passes the test.
let isOver = v => v > 40
let a = [1, 30, 41, 29, 10, 13]
console.log(a.some(isOver)) // true
.includes()Test if an array contains a value.
let a = [1, 2, 3]
let b = a.includes(2)
console.log(b) // true
Creating
CommandDescription
Array.of()Creates a new array from the given arguments.
Array.of('foo', 'bar')
// ['foo', 'bar']
Array.from()Creates a new array from an array-like or iterable object.
console.log(Array.from('foo')) // ['f', 'o', 'o']
console.log(Array.from([1, 2, 3], x => x + x)) // [2, 4, 6]
.fill()Change all elements in an array to a static value.
let a = [1, 2, 3, 4]
let b = a.fill(0, 2, 4)
console.log(b) // [1, 2, 0, 0]
Morphing
CommandDescription
.entries()Returns an iterator object with key/value pairs for each index in the array.
let a = ['a', 'b', 'c']
let iterator = a.entries()
console.log(iterator.next().value) // [0, "a"]
console.log([...iterator]) // [[0, "a"], [1, "b"], [2, "c"]]`]
.values()Returns an iterator object with values for each index in the array. Changes the data type from array to iterator.
let a = ['a', 'b', 'c']
let iterator = a.values()
for (const v of iterator) { console.log(v) } // a, b, c
.keys()Returns an iterator object with keys for each index in the array. Changes the data type from array to iterator.
let a = ['a', 'b', 'c']
let iterator = a.keys()
for (const v of iterator) { console.log(v) } // 1, 2, 3
.join()Turn array into a string by joining the element together.
let a = ['foo', 'bar', 'baz']
a.join() // foo,bar,baz
a.join('-') // foo-bar-baz
.toString()Turn array or any other object into a string.
let a = ['foo', 'bar', 'baz']
a.join() // foo,bar,baz
.toLocaleString()Stringifies an array in a locale sensitive way.
let a = [1, 'a', new Date('21 Dec 1997 14:12:00 UTC')]
a.toLocaleString('en', { timeZone: 'UTC' }) // 1,a,12/21/1997, 2:12:00 PM
a.toLocaleString('de') // '1,a,21.12.1997, 15:12:00'
Information
CommandDescription
.at() ⚠️Takes in integer value and returns the array element at that index. -1 returns the last element. ⚠️ Experimental technology.
let x = ['a', 'b', 'c']
console.log(a.at(1)) // b
console.log(a.at(-1)) // c
.lengthGets the element count of an array.
let x = ['a', 'b', 'c']
console.log(a.length) // 3
Array.isArray()Tests if a given variable is an array.
let a = ['a', 'b']
console.log(Array.isArray(a)) // true
Misc.
CommandDescription
.flat()Flatten a nested array.
let a = [0, 1, 2, [3, 4]]
let b = a.flat()
console.log(b) // [0, 1, 2, 3, 4]
.reverse()Reverses the order of an array.
let a = [1, 2, 3, 4]
a.reverse()
console.log(a) // [4, 3, 2, 1]

About array methods

JavaScript has about 36 array methods in total. Hope this searchable guide comes handy when you’re looking for the right method to use.

Use with Alfred

A screen shot of Alfred app’s search bar

You can quickly search this guide from Alfred if you setup a custom search. Click here to add it automatically. Or see instructions below how to add it manually.

How to add custom Alfred search manually
  1. Pop open Alfred settings.
  2. Go to "Web Search".
  3. Click "Add Custom Search".
  4. In the "Search URL" field paste: https://clubmate.fi/tmux-cheat-sheet?s={query}.
  5. Name it something like: "Search tmux cheat sheet for {query}"
  6. Give it a suitable keyword like "tmux", and save.
  7. Then type something like "tmux kill" into Alfred, et voilà.
A screen shot of Alfred app
How to add tmux cheat sheet as custom search engine in Alfred

Comments would go here, but the commenting system isn’t ready yet, sorry. Tweet me @intterne if you want to make a correction etc.

  • © 2022 Antti Hiljá
  • About
  • Follow my new Twitter account → @intterne
  • All rights reserved yadda yadda.
  • I can put just about anything here, no one reads the footer anyways.
  • I love u!