To insert a value back into an array (at the same position) after you spliced it, can in general be done like this:
// delete:
var deleted = fruits.splice(i, 1);
// restore:
fruits.splice(i, 0, deleted);
Note that deleted
is an array with one element here.
It can also done by taking a kind of backup of the original array:
// backup
var backup = fruits.slice(); // copy
// delete:
fruits.splice(i, 1);
// restore:
fruits = backup;
Undo Stack
To support multiple undo actions, you could use an undo stack, which would just keep track of all the versions of your array. When the user performs an undo-action, the previous version is popped from that stack. This way you can undo more than one removal:
var fruits = ['Apples', 'Bananas', 'Grapes', 'Watermelons', 'Tomatoes'];
var undoStack = [];
function showFruits() {
$('#fruits').html('').append(
// translate the array to a list of LI elements with delete buttons
fruits.map(function(fruit) {
return $('<li>').text(fruit).append(
$('<button>').addClass('delete').text('Delete'));
})
);
}
$(document).on('click', 'button.delete', function () {
undoStack.push(fruits.slice()); // save a copy of the current array on the stack
fruits.splice($(this).parent().index(), 1); // remove from array at index
showFruits(); // update display
});
$('#undo').click(function () {
if (!undoStack.length) return; // cannot undo
fruits = undoStack.pop(); // get previous state
showFruits(); // update display
});
showFruits(); // show initial list
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id="fruits"></ul>
<button id="undo">Undo</button>
More memory efficient alternative
If you are troubled by the memory usage of storing the complete array each time you delete an element, you could use the following alternative functions, which will only store the index and deleted value at every delete action:
$(document).on('click', 'button.delete', function () {
var i = $(this).parent().index(); // get index where to delete
var deleted = fruits.splice(i, 1); // remove from array at that index
undoStack.push([i, deleted]); // save the index and value on the stack
showFruits(); // update display
});
$('#undo').click(function () {
if (!undoStack.length) return; // cannot undo
var restore = undoStack.pop(); // get information for re-inserting
fruits.splice(restore[0], 0, restore[1]); // insert the value
showFruits(); // update display
});
If you would use the undo principle also for other modifications, like undoing an insert, or a modification of the label, then the first solution would not need much modification, while the more memory-efficient one would need a bit more.
For a more generic and elaborated solution on undo/redo operations on any object (not only arrays), see How to version control an object?