Splice Array Method Javascript
- The
splice method is used to modify an array by adding, removing, or replacing elements.
- It directly changes the original array.
- Returns an array of the removed elements.
Syntax
array.splice(start, deleteCount, item1, item2, ...)
start: The index at which to start changing the array.
deleteCount (optional): The number of elements to remove from the array, starting at start. if omitted, it removes all elements from start to the end.
item1, item2, ... (optional): Elements to add to the array, starting at start.
Example
const numbers = [1, 2, 3, 4, 5];
// Removing elements
const removed = numbers.splice(2, 2);
console.log(numbers); // Output: [1, 2, 5]
console.log(removed); // Output: [3, 4]
// Adding elements
numbers.splice(2, 0, 3, 4);
console.log(numbers); // Output: [1, 2, 3, 4, 5]