Skip to content

Instantly share code, notes, and snippets.

@varemenos
Created April 2, 2014 12:35
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save varemenos/9933199 to your computer and use it in GitHub Desktop.
Save varemenos/9933199 to your computer and use it in GitHub Desktop.
Function to move an Array item to another position of that Array
var t = [ 'a', 'b', 'c', 'd', 'e'];
Array.prototype.move = function (source, destination) {
// if source and destination are the same
if (source === destination) {
// then there is no need to move
return;
}
// if the source is smaller than 0 or the destination is larger than the size of the array
if (source < 0 || source > this.length - 1 || destination > this.length - 1) {
// then the statement is invalid
throw new RangeError('The \'source\' or \'destination\' parameters are out of range');
}
var value2move = this[source];
this.splice(source, 1);
this.splice(destination, 0, value2move);
};
t.move(4, 0);
console.log(t);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment