According to this reply, https://stackoverflow.com/questions/5306680/move-an-array-element-from-one-array-position-to-another, 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]);
};
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, exchange the "splice" in the last line for "Slice".
UPDATE
Instead of creating this move method in the Array base domain class of all 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 that, 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 code as the Array#move above. 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: http://jsfiddle.net/rkzs8teg/2/
UPDATE 2
In fact, 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();
}
Follows the use of it: http://jsfiddle.net/rkzs8teg/3/
Just to better understand, where does this array come from? You want to create the array manually and make HTML respect its order?
– bfavaretto
I want to manipulate the existing html, transforming it into an array, through the array changing the position of the elements
– leodario