tags:

views:

91

answers:

5
+4  Q: 

Reordering arrays

Hi,

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 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.

Any help would be appreciated.

+1  A: 

Change 2 to 1 as the first parameter in the splice call when removing the element:

var tmp = playlist.splice(1,1);
playlist.splice(2,0,tmp);
Trevor
A: 

You could always use the sort method, if you don't know where the record is at present:

playlist.sort(function (a, b) {
    return a.artist == "Lalo Schifrin" 
               ? 1    // Move it down the list
               : 0;   // Keep it the same
});
Andy E
@Daniel: thanks for the fix, trying to concentrate on about 7 things at once here ;-)
Andy E
+1  A: 

If you know the indexes you could easily swap the elements, with a simple function like this:

function swapElement(array, indexA, indexB) {
  var tmp = array[indexA];
  array[indexA] = array[indexB];
  array[indexB] = tmp;
}

swapElement(playlist, 1, 2);
// [{"artist":"Herbie Hancock","title":"Thrust"},
//  {"artist":"Faze-O","title":"Riding High"},
//  {"artist":"Lalo Schifrin","title":"Shifting Gears"}]

Array indexes are just properties of the array object, so you can swap its values.

CMS
+1  A: 

Syntax of splice is array.splice(index,howmany,element1,.....,elementX)

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
Matt
A: 

Thanks for the answers.

I found out that by using splice, like I did originally:

var tmp = playlist.splice(1,1);
playlist.splice(2,0,tmp);

Works, but adds brackets to the moved element, like this:

playlist = [
{artist:"Herbie Hancock", title:"Thrust"},
{artist:"Faze-O", title:"Riding High"},
[{artist:"Lalo Schifrin", title:"Shifting Gears"}]
]

Which screws things up. Why does it add brackets to the element, and can I avoid that?

Thanks!

Wurlitzer
splice returns an array, so tmp will be an array with one element in this case. The second splice adds that array to the playlist. Hence the "brackets". You can instead do playlist.splice(2,0,tmp[0]), to add the object inside the tmp array instead of the entire tmp array.
Lars
Thanks! That did the trick.
Wurlitzer