Skip to content

Instantly share code, notes, and snippets.

@robertoentringer
Created February 13, 2019 21:39
Show Gist options
  • Save robertoentringer/3d4ab0a59a366274162d3da213da811a to your computer and use it in GitHub Desktop.
Save robertoentringer/3d4ab0a59a366274162d3da213da811a to your computer and use it in GitHub Desktop.
JavaScript Array move
// Append a move method to the Array prototype
Array.prototype.move = function(from, to) {
this.splice(to, 0, this.splice(from, 1)[0]);
return this;
};
// Start with an existing array
var orig = ["Sam", "Tom", "Ben", "Sophie"];
// Use the new method to move the last item in the array to the first position
var spliced = orig.move(orig.length - 1, 0);
console.log(spliced);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment