Reordering arrays

arrays, javascript, sorting

Solution

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:

Problem

Say, I have an array that looks like this: ``` var playlist = [ {artist:"Herbie Hancock", title:"Thrust"}, {artist:"Lalo Schifrin", title:"Shifting Gears"}, {artist:"Faze-O", title:"Riding High"} ]; ``` How can I move an element to another position? I want to move for example, `{artist:"Lalo Schifrin", title:"Shifting Gears"}` to the end. I tried using splice, like this: ``` var tmp = playlist.splice(2,1); playlist.splice(2,0,tmp); ``` But it doesn't work.

Original source

Related problems