There are a ton of array methods that JavaScript provides. Here is a reference to some useful ones in different categories
To add/remove elements:
-
push(...items)
– adds items to the end of the array -
pop()
– extracts an item from the end of the array -
shift()
– extracts an item from the beginning of the array -
unshift(...items)
– adds items to the beginning -
slice(start, end)
– creates a new array, copies elements from position start till end (not inclusive) into it. -
concat(...items)
– returns a new array: copies all members of the current one and adds items to it. If any of items is an array, then its elements are taken.
To transform an array
-
map(func)
- creates a new array from results of callingfunc
for every element. -
sort(func)
- sorts the array in-place, then returns it. -
reverse()
- reverses the array in-place, then returns it. -
split/join
- convert a string to array and back. -
reduce(func, initial)
- calculate a single value over the array by callingfunc
for each element and passing an intermediate result between the calls.
To search in an array
-
indexOf/lastIndexOf(item, pos)
- look foritem
starting from positionpos
, return the index or-1
if not found. -
includes(value)
- returnstrue
if the array hasvalue
, otherwisefalse
. -
find/filter(func)
- filter elements through the function, return first/all values that make it returntrue
. -
findIndex
- is likefind
but returns the index instead of a value.
Iterating in an array
-
forEach(func)
-- callsfunc
for every element.
For a more detailed reference about arrays and array methods check out MDN
Top comments (0)