Skip to content

Instantly share code, notes, and snippets.

@Orbifold
Created October 23, 2014 07:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Orbifold/63e5f14d81bb09009636 to your computer and use it in GitHub Desktop.
Save Orbifold/63e5f14d81bb09009636 to your computer and use it in GitHub Desktop.
Move an item in place in an array.
Array.prototype.move = function (pos1, pos2) {
var i, tmp;
pos1 = parseInt(pos1, 10);
pos2 = parseInt(pos2, 10);
if (pos1 !== pos2 &&
0 <= pos1 && pos1 <= this.length &&
0 <= pos2 && pos2 <= this.length) {
// save element from position 1
tmp = this[pos1];
// move element down and shift other elements up
if (pos1 < pos2) {
for (i = pos1; i < pos2; i++) {
this[i] = this[i + 1];
}
}
// move element up and shift other elements down
else {
for (i = pos1; i > pos2; i--) {
this[i] = this[i - 1];
}
}
// put element from position 1 to destination
this[pos2] = tmp;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment