Modify (Mutating) Methods
Modify (Mutating) Methods
Section titled “Modify (Mutating) Methods”These change the original array (important in interviews)
splice()
Section titled “splice()”Adds/removes elements at a specific index.
const arr = [10, 20, 30, 40];arr.splice(1, 2);// removes 2 items starting at index 1// arr = [10, 40]e:** O(n) Mutates original? Yes### Insert using splice
const arr = [10, 30];arr.splice(1, 0, 20);// [10, 20, 30]push()
Section titled “push()”Adds to end.
arr.push(50);Time: O(1) amortized Mutates? Yes
Removes from end.
arr.pop();Time: O(1) Mutates? Yes
unshift()
Section titled “unshift()”Adds to start.
arr.unshift(5);Time: O(n) Mutates? Yes
shift()
Section titled “shift()”Removes from start.
arr.shift();Time: O(n) Mutates? Yes
reverse()
Section titled “reverse()”Reverses the array in place.
arr.reverse();Time: O(n) Mutates? Yes
sort()
Section titled “sort()”Sorts the array in place.
arr.sort((a, b) => a - b);Time: O(n log n) Mutates? Yes
Always pass comparator for numbers.