Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Splice an array - with undo
function spliceRevertable() {
var self = this
, revertArray = [arguments[0], arguments.length - 2]
, result = revertArray.splice.apply(this, arguments)
, revertArguments = revertArray.concat(, 2))
result.revert = funtion() {
return revertArguments.splice.apply(self, revertArguments)
return result
Copy link

arnehormann commented Feb 19, 2012

Splice - The ultimate array function

Array.splice is an incredibly powerful function. It can be used for insertion, deletion and updates. Honestly, it provides all opertions you'll ever need when you want to modify an Array.

Here's the signature: [].splice(index, numberRemoved, ...elements to be inserted...).
It returns an array containing the removed elements and modifies the array it's called on.

So... for operations on one element:

  • insert: array.splice(insertionIndex, 0, newElement)
  • prepend: array.splice(0, 0, newElement)
  • append / push: array.splice(array.length, 0, newElement)
  • remove: array.splice(removalIndex, 1)
  • pop: array.splice(array.length - 1, 1)
  • replace: array.splice(replacementIndex, 1, newElement)

You can even clear the whole array with array.splice(0, array.length).

With splice as your only method for modifications, you can use spliceRevertable like this:, regular splice arguments) (or - if you really want to be able to use it on every Array - Array.spliceRevertable = spliceRevertable;).
When you call revert() on the result, it will undo the operation leading to the result and the change and return the change.

I use this for optimistic UI updates. But you have to be carefull: only the last call can cleanly be reverted - or the calls have to be reverted in the reverse order of original calls. Otherwise, the first argument (index) will mess up your array.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment