Thanks for the help on my other question (not sure if that will solve the problem but I'll check it out).
Here's a possible solution to your problem. Note that it adds a method to the Array object, so you can use it with any array (assuming it works). Also note that it only switches two elements - so if you use a delta of -3, for example, it will switch the two items but will not "bump up" the in between items - that is left as an exercise for the reader.
Code:
Array.prototype.move_element = function(index, delta) {
// This method moves an element within the array
// index = the array item you want to move
// delta = the direction and number of spaces to move the item.
//
// For example:
// move_element(myarray, 5, -1); // move up one space
// move_element(myarray, 2, 1); // move down one space
//
// Returns true for success, false for error.
var index2, temp_item;
// Make sure the index is within the array bounds
if (index < 0 || index >= this.length) {
return false;
}
// Make sure the target index is within the array bounds
index2 = index + delta;
if (index2 < 0 || index2 >= this.length || index2 == index) {
return false;
}
// Move the elements in the array
temp_item = this[index2];
this[index2] = this[index];
this[index] = temp_item;
return true;
}
//--------------------------------------------------
// Test it out
myArray = Array("item one","item two","item three","item four")
if ( myArray.move_element(3, -1) ) {
// Success, display the array contents
alert("myArray = " + myArray);
} else {
// Failure
alert("move_element returned false");
}