Array methods cheatsheet

Download image version

Adding/Removing elements

  • push(...items) add items to the end

const arr = [1, 2, 3];
arr.push(4);
// arr = [1, 2, 3, 4]
  • pop() extracts an element from the end

const arr = [1, 2, 3];
arr.pop();
// arr = [1, 2]
  • unshift(...items) add items to the beginning (bad for performance)

const arr = [1, 2, 3];
arr.unshift(0);
// arr = [0, 1, 2, 3]
  • shift() extracts from the beginning

const arr = [1, 2, 3];
arr.shift();
// arr = [2, 3]
  • concat(...items) returns a new array: copy of the current array + items

  • splice(pos, count, ...items) at index pos deletes count elements and inserts items

  • slice(start, end) creates a new array, copies elements from index start till end (not inclusive) into it


Search among elements

  • indexOf / lastIndexOf(item, pos) look for item starting from index pos, return it's index or -1 if not found. Method lastIndexOf() searches from right to left

  • includes(value) returns true if the array has value, else false

  • find / findIndex(func(item, index, arr)) func() is called for each element of the array. If the func() returns true, the search is interrupted and item is returned, else - undefined

  • filter(func(item, index, arr)) the method is similar to find(), but filter() returns an array of all matching elements


Iteration of elements

  • forEach(func(item, index, array)) calls func() for every element in array, does not return anything


Transform the array

  • map(func(item, index, array)) calls the func() for each element of the array and returns the array of results

  • sort(func()) sorts the array changing it's element order, func() defining the sorting order (optional).

  • reverse() reverse the order of the elements of the current array

  • join(separator) / string.split(separator) convert an array to string / a string to array

  • reduce / reduceRight(func(accumulator, current, index, array), initial) calculate a single value over the array by calling func() for each element and passing an intermediate result between the calls


Bonus

  • Array.isArray(variable) checks variable for being an array, return true/false

  • some / every(fn()) The function fn() is called on each element of the array similar to map(). If any/all results are true - return true, otherwise - false

  • fill(value, start, end) fills the array with repeating value from start to end positiion

  • flat(depth) create a new flat array from a multidimensioanl array

Last updated