Search code examples
javascriptarrayssplice

How to "undo" a deleted element with splice?


When I have an array and I use splice to remove, let's say, the last element of the array. Is there a chance to create for example a button and when I click on it, it undoes the deleted action? Like using Ctrl + Z when write code and jump back in time? That means give me back the deleted element with all its characteristics?


Solution

  • Array.splice allows you to delete or insert elements, it also returns the removed elements when deleting. If you capture the deleted elements you can easily add them back:

    let arr = [1,2,3,4,5,6];
    // remove 1 element from index 1 ("2")
    let removed = arr.splice(1, 1);
    // add "2" back to position 1
    arr.splice(1, 0, ...removed);
    
    console.log(arr);

    If you don't have access to ES6's spread operator, you could use .shift() to get the first element out of removed:

    let arr = [1,2,3,4,5,6];
    // remove 1 element from index 1 ("2")
    let removed = arr.splice(1, 1);
    // add "2" back to position 1
    arr.splice(1, 0, removed.shift());
    
    console.log(arr);