JavaScript: All Of The Essential Array Methods
An array is used to store multiple elements in a single variable. Array’s are usually used when order matters. Each element is denoted by an index, starting at zero.
Basic Methods
- .push(): adds an element to the end of an array, and returns the new number of elements
- .unshift(): adds an element to the beginning of an array, and returns the new number of elements
- .pop(): removes an element from end of an array, and returns the removed element
- .shift(): removes an element from the beginning of an array, and returns the removed element
- .concat(): takes multiple array’s and merges them together, and returns new array
- indexOf(): returns the index of the first occurrence of a value in an array, or -1 if value is not found
- .slice(): extracts and return a copy of part of an array, takes in up to two arguments. Argument 1: the index of the selected element Argument 2:(optional) the ending index (the default value is array.length, extracts up to but not including end)
- .splice(): changes the contents of an array by adding/removing elements, takes in up to two integer arguments, and numerous elements following. returns the removed element/elements. Argument 1: the index of the beginning element Argument 2:(optional) the number of elements, following argument 1, that will be deleted. (the default value is array.length, meaning all following elements will be deleted) Argument 3:(optional) the element/elements that will be added to the array, at the selected location.
- .sort() O(N * log N): converts elements to strings, and sorts elements in an array in ascending order.
Compare Intergers
.sort((a, b) => a - b)
Looping through an Array: O(N)
- for & for of: want to run the same code on each element in an array
array = [ 1,2,3,1 ]for (let i = 0; i < array.length; i++){
console.log(array[i] + 2)
}
//3 4 5 3for (let char of array){
console.log(char + 2)
}
//3 4 5 3Convert Array Into an Object (histogram)let histogram = {}
for (let char of array){
histogram[char] = (histogram[char] || 0) + 1
}
console.log(histogram)
//{ '1': 2, '2': 1, '3': 1 }
- .some(): tests if at least one element in the array meets the condition, and returns boolean
[2, 1, 1, 6, 8].some(item => item > 7) // true
[1, 2, 3, 4, 5].some(item => item > 7) // false
- .every(): tests if at all elements in the array meet the condition, and returns boolean
[2, 1, 1, 6, 8].every(item => item > 7) // false
[2, 2, 3, 4, 5].every(item => item > 1) // true
- .fill(): changes all elements in an array to the value provided. Takes in up to three parameters. The Value, Start Index (optional, will default to 0), End Index (optional, will default to array.length)
[2, 1, 1, 6, 8].fill(0,1,3) // [ 2, 0, 0, 6, 8 ]
- .includes(): determines if an array includes a certain value, returns boolean. Takes in up to two parameters. The Value, Index (optional).
[2, 1, 1, 6, 8].includes(2,0) // true
[2, 1, 1, 6, 8].includes(2,1) // false
- .reverse(): “flip” the array
[2, 1, 1, 6, 8].reverse() // [ 8, 6, 1, 1, 2 ]
- .flat(): creates a new array…. with all sub-array elements merged into a new array. Takes in depth as an optional element, with the default of 1
[ 1, 2, [[[3, 4]]]].flat() //[ 1, 2, [[3, 4]]]
[ 1, 2, [[[3, 4]]]].flat(2) //[ 1, 2, [3, 4]]
- .reduce(): executes a “reducer”function (that you provide) on each element of the array, resulting in single output value. Takes in up to four arguments. The “accumulator”(optional) accumulates callback’s return values. The “currentValue”(optional) value of the selected element. “currentIndex”(optional) index of the selected element. The “array”(optional) the entire array.
initialValue
may also be added to the end of the function.
Sum of elements in an array:
[5,6,7,8].reduce((accumulator, currentValue) => accumulator + currentValue)
//26let initialValue = 20
[5,6,7,8].reduce((accumulator, currentValue, currentIndex, array) => accumulator + currentValue, initialValue)
//46
All of the below methods have callback functions that accept four optional arguments. These include the following, in the following order, Current Value, Index, Array, ThisArg (Value to use as this
when executing callback).
- .map(): creates a new array from the result of the callback function. The new array will always have the same number of arguments as the starting array
- .flatMap(): identical to a
map()
followed by aflat()
of depth 1, but slightly more efficient than calling those two methods separately
['hello my name is', '', 'how are you?'].map(x => x.split(' '))
// [[ 'hello', 'my', 'name', 'is' ],[ '' ],[ 'how', 'are', 'you?' ]]['hello my name is', '', 'how are you?'].flatMap(x => x.split(' '))
//['hello', 'my','name', 'is','','how','are','you?']*******************************************************************
- .filter(): creates a new array with all the elements that pass the test implemented by the
callback
function
[1,2,3,4,5,6,7].filter(num => num > 5) // [ 6, 7 ]
- .find(): returns the value of the first element in the provided array that satisfies the
callback
function. If no values satisfies the testing function,undefined
is returned.
[1,2,3,4,5,6,7].find(num => num > 5)// 6
- .findIndex(): returns the index of the first element in the provided array that satisfies the provided testing function. If no values satisfies the testing function,
undefined
is returned.
[1,2,3,4,5,6,7].findIndex(num => num > 5)// 5
- .forEach(): executes a provided function once for each element. Has no implicit return.
[1,2,3,4,5,6,7].forEach(num => console.log(num * -1))
// -1 -2 -3 -4 -5 -6 -7
- Array.from(): static method creates a new, shallow-copied
Array
instance from an array-like or iterable object.
const newArray = Array.from('hello');//
console.log(newArray)//['h', 'e', 'l', 'l', 'o']
- Spread Operator
const arrayOne = [1, 2, 3, 4];
const arrayOne = [5, 6, 7, 8];
const newArray = [...arrayOne, ...arrayOne];
console.log(newArray) //[1, 2, 3, 4, 5, 6, 7, 8]
BIG O of Arrays Searching:O(N)
Access:O(1)
Insertion:It depends...
Removal:It depends...**insert/remove at end is 0(1), insert/remove at the beginning 0(N) because we need to re-index
other useful methods:
.toString()