Array Accessors and Mutators Flashcards
(24 cards)
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 element to the front of an Array
array.unshift(element)
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, mutates original array.
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)
Create an array of all of the indexes of an array
array.keys()
Create and return a new string by concatenating all of the elements in this array,
array.join()
const elements = [“Fire”, “Air”, “Water”];
elements.join(“-“); // Expected output: “Fire-Air-Water”
Returns the last index at which a given element can be found in the array,
const animals = [“Dodo”, “Tiger”, “Penguin”, “Dodo”];
animals.lastIndexOf(‘Dodo’) // 3
Reverse an array in place, returns a reference to the original array
array.reverse()
Removes the first element of an array and returns that element
array.shift()
Sorts an array in place, returns a reference to the original array
array.sort()
Returns an iterator with the values of given array
array.values()
Replace a value with the given index. Returns a new array
array.with()
Returns a string representing the elements of an array using Locale
array.toLocaleString()
const array1 = [1, "a", new Date("21 Dec 1997 14:12:00 UTC")]; const localeString = array1.toLocaleString("en", { timeZone: "America/New_York" });