Array methods cheatsheet
Adding/Removing elements
push(...items) add
items
to the end
pop() extracts an element from the end
unshift(...items) add
items
to the beginning (bad for performance)
shift() extracts from the beginning
concat(...items) returns a new array: copy of the current array +
items
splice(pos, count, ...items) at index
pos
deletescount
elements and insertsitems
slice(start, end) creates a new array, copies elements from index
start
tillend
(not inclusive) into it
Search among elements
indexOf / lastIndexOf(item, pos) look for
item
starting 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
variable
for 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
value
fromstart
toend
positiion
flat(depth) create a new flat array from a multidimensioanl array
Last updated