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.
The syntax of
Array.spliceis:Where:
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:
Then just use:
Diagram: