Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
122
rated 0 times [  123] [ 1]  / answers: 1 / hits: 175415  / 15 Years ago, sun, march 14, 2010, 12:00:00

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.


More From » arrays

 Answers
86

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


[#97347] Wednesday, March 10, 2010, 15 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
byron

Total Points: 616
Total Questions: 101
Total Answers: 91

Location: Reunion
Member since Wed, Apr 14, 2021
3 Years ago
byron questions
Wed, Jan 26, 22, 00:00, 2 Years ago
Sat, Jun 6, 20, 00:00, 4 Years ago
Thu, Nov 7, 19, 00:00, 5 Years ago
Wed, Sep 11, 19, 00:00, 5 Years ago
;