Array methods cheatsheet
Adding/Removing elements
push(...items) add
itemsto 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
itemsto 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
posdeletescountelements and insertsitems
slice(start, end) creates a new array, copies elements from index
starttillend(not inclusive) into it
Search among elements
indexOf / lastIndexOf(item, pos) look for
itemstarting from indexpos, return it's index or -1 if not found. MethodlastIndexOf()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 thefunc()returns true, the search is interrupted and item is returned, else - undefined
filter(func(item, index, arr)) the method is similar to
find(), butfilter()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
variablefor being an array, return true/false
some / every(fn()) The function
fn()is called on each element of the array similar tomap(). If any/all results are true - return true, otherwise - false
fill(value, start, end) fills the array with repeating
valuefromstarttoendpositiion
flat(depth) create a new flat array from a multidimensioanl array
Last updated