Reordering arrays

The syntax of Array.splice is:

yourArray.splice(index, howmany, element1, /*.....,*/ elementX);

Where:

  • index is the position in the array you want to start removing elements from
  • howmany is how many elements you want to remove from index
  • element1, …, elementX are elements you want inserted from position index.

This means that splice() can be used to remove elements, add elements, or replace elements in an array, depending on the arguments you pass.

Note that it returns an array of the removed elements.

Something nice and generic would be:

Array.prototype.move = function (from, to) {
  this.splice(to, 0, this.splice(from, 1)[0]);
};

Then just use:

var ar = [1,2,3,4,5];
ar.move(0,3);
alert(ar) // 2,3,4,1,5

Diagram:

Algorithm diagram

Leave a Comment