A cheatsheet of array methods:
- To add/remove elements:
push(...items)– adds items to the end,pop()– extracts an item from the end,shift()– extracts an item from the beginning,unshift(...items)– adds items to the beginning.splice(pos, deleteCount, ...items)– at indexposdeletedeleteCountelements and insertitems.slice(start, end)– creates a new array, copies elements from positionstarttillend(not inclusive) into it.concat(...items)– returns a new array: copies all members of the current one and addsitemsto it. If any ofitemsis an array, then its elements are taken.
- To search among elements:
indexOf/lastIndexOf(item, pos)– look foritemstarting from positionpos, return the index or-1if not found.includes(value)– returnstrueif the array hasvalue, otherwisefalse.find/filter(func)– filter elements through the function, return first/all values that make it returntrue.findIndexis likefind, but returns the index instead of a value.
- To transform the array:
map(func)– creates a new array from results of callingfuncfor 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 callingfuncfor each element and passing an intermediate result between the calls.
- To iterate over elements:
forEach(func)– callsfuncfor every element, does not return anything.
- Additionally:
Array.isArray(arr)checksarrfor being an array.
Please note that methods
sort, reverse and splice modify the array itself.
No comments:
Post a Comment