According to this answer, link
, you can use this code:
Array.prototype.move = function (old_index, new_index) {
if (new_index >= this.length) {
var k = new_index - this.length;
while ((k--) + 1) {
this.push(undefined);
}
}
this.splice(new_index, 0, this.splice(old_index, 1)[0]);
};
In this way, the code to use the above method would be:
[1, 2, 3].move(0, 1) # retorna [2, 1, 3]
If you want to return a copy, and do not modify the original array, change the "splice" to "slice" in the last line.
UPDATE
Instead of creating this method moves in the base domain class Array of the entire javascript, you can implement the method only in your array.
In this case, we would have a method to change the order of your array with the elements, and another to render the new format, ie change the DOM when the reordering is done. With this, I wrote two methods:
$(document).ready(function(){
var elems = $(".departamento h5, .departamento ul");
elems.changeOrder = function (old_index, new_index) {
if (new_index >= this.length) {
var k = new_index - this.length;
while ((k--) + 1) {
this.push(undefined);
}
}
this.splice(new_index, 0, this.splice(old_index, 1)[0]);
};
elems.reflux = function(){
var newListOfElements = this.clone();
var oldListOfElements = $(this.selector);
for(var i=0; i < newListOfElements.length; i++){
$(newListOfElements[i]).insertAfter(oldListOfElements[i]);
}
$(oldListOfElements).remove();
}
elems.changeOrder(2, 0); // [2] == Titulo Cerveja vai para [0]
elems.changeOrder(3, 1); // [3] == Lista de cervejas vai para [1]
elems.reflux(); // Após trocar a ordem, refaz o DOM de acordo com a ordem;
});
The first, #changeOrder, is a method that contains the same Array # code moves up. The second is the #reflux () method. Basically, it inserts new clone elements on the screen considering the new ordering and then deletes the old elements, from the old ordering.
I put the code here: link
UPDATE 2
In fact, a more optimized code for the #reflux method would look like this:
elems.reflux = function(){
var oldListOfElements = $(this.selector),
newListOfElements = this.clone();
$(newListOfElements).insertAfter(oldListOfElements.last());
$(oldListOfElements).remove();
}
Here's how to use it: link