Array Accessors and Mutators Flashcards
Access (index into) an Array item (index lookup)
array[0]
Add to the end of an Array
array.push()
Remove from the end of an Array
array.pop()
Add to the front of an Array
array.unshift()
Remove from the front of an Array
array.shift()
Find the index of an item in the Array
array.indexOf(‘item’)
Remove an item by index position
array.splice(pos, deleteCount, item) (mutable) let array = [1,2,3]
array. splice(1, 0, 3) // [1,3,2,3]
array. splice(1, 1, 3) // [1,3,3]
Copy section of an Array
array.slice(start, end) (immutable - shallow copy) let array = ['cat', 'dog', 'mouse']
array. slice(1) // [‘dog’, ‘mouse’]
array. slice(0,2) // [‘cat’, ‘dog’]
Convert the Array to a String
array.toString() [1, 2, ‘a’, ‘1a’] -> “1,2,a,1a”
Check for a specific value
array.includes()
Convert to separated String
array.join()
[‘Fire’, ‘Air’, ‘Water’] .join() -> “Fire,Air,Water”
.join(‘-‘) -> “Fire-Air-Water”
Populate all elements of an array to a static value
array.fill()
Array(3).fill({}) // [{}, {}, {}]
Merge two or more arrays into a new array (immutable)
array.concat() or spread [...array1, ...array2] const array1 = ['a', 'b', 'c']; const array2 = ['d', 'e', 'f']; const array3 = array1.concat(array2); // ["a", "b", "c", "d", "e", "f"]
Merge two arrays into an existing array (mutable)
existingArray.push.apply(existingArray, newArray)
let existingArray = [1,2,3]
let newArray = [4,5,6]
existingArray.push.apply(existingArray, newArray) // [1,2,3,4,5,6]
Combine nested arrays into single flattend array
array.flat() (immutable - returns new array)
Map over and array and then flatten
array.flatMap(() => {})
Create an array of all of the indexes of an array
array.keys()