Solution: You can solve your problem by using nested Array.Splice()
methods. I would make this an extension method on arrays.
Array.prototype.move = function(from, to) {
this.splice(to, 0, this.splice(from, 1)[0]);
};
Explanation: The inner splice()
is essentially saying take the item you are wanting to move, remove it from the array, and use the value of that item in the outer splice()
. The outer splice()
is saying to insert the item you just removed from the array at the index you specified in to
.
Array.prototype.move
is Javascript's way of creating an extension method called move
on array objects. Any code that has access to this function can call move(from, to)
on any array (e.g. myArray.move(2, 0)
). So I would put this somewhere global so all your code can see it!
Example:
var letters = ["A", "B", "C", "D", "E"];
letters.move(2, 0);
// letters is now ["C", "A", "B", "D", "E"]