Arrays Flashcards
How is an array declared?
let arr = []
What method is used to append an element to the end of an array?
.push(value)
What method is used to remove an element from the end of an array?
.pop()
How do you return an element from a specific index?
arr.at(index)
How do you set an element at a specific index?
arr[index] = value;
How do you convert an array to a string of comma separated values?
array.toString()
How do you remove the first element from an array?
shift()
This method removes the first element from an array and returns that removed element. It changes the length of the array.
How do you add one or more elements to the beginning of an array?
unshift(…items) -
Adds one or more elements to the beginning of an array and returns the new length of the array.
How do you remove an element from an array at a specific index without changing the length of the array?
delete arr[index] - Removes an element at the specified index. This operation leaves a hole (undefined element) in the array and does not change the array’s length.
How do you merge two or more arrays into a new array?
arr.concat(…values) - Merges two or more arrays or values into a new array without modifying the original arrays.
How do you create a new array with all sub-array elements concatenated into it recursively up to a specified depth?
arr.flat(depth) - Creates a new array with all sub-array elements concatenated into it up to the specified depth. The default depth is 1.
How do you change the contents of an array by removing or replacing existing elements and/or adding new elements?
arr.splice(start, deleteCount, …items) - Changes the contents of an array by removing or replacing existing elements and/or adding new elements in place.
How do you return a shallow copy of a portion of an array into a new array object in JavaScript?
let new_arr = arr.slice(start,end) - Returns a shallow copy of a portion of an array into a new array object. It selects from start to end (end not included). The original array is not modified.
How do you find the first index of a specified element in an array?
indexOf(searchElement, fromIndex) - Returns the first index at which a given element can be found in the array, or -1 if it is not present. The search starts from fromIndex if provided.
How do you find the last index of a specified element in an array?
lastIndexOf(searchElement, fromIndex) - Returns the last index at which a given element can be found in the array, or -1 if it is not present. The search starts backward from fromIndex.