Pregunta

I have an array of objects and I want to swap the position of two elements in the array. I tried this:

var tempObject = array.splice(index, 1, array[index + 1]);
array.splice(index+1, 1, tempObject);

But it doesn't seem to work properly as it results in some weird errors. For example, I am unable to use methods of the object. Calling array[x].getName results in an error.

Can any body lend a helping hand here?

Just in case it is important, I have used object.prototype to add the methods.

¿Fue útil?

Solución

The bug in your code is that splice returns an array of items, not a single item. Since you are extracting a single item, you could do:

var tempObject = array.splice(index, 1, array[index + 1])[0]; // get the item from the array
array.splice(index+1, 1, tempObject);

This answer provides a shorter version, also using splice:

array[index] = array.splice(index+1, 1, array[index])[0];

Another very interesting answer is both short and fast:

function identity(x){return x};

array[index] = identity(array[index+1], array[index+1]=array[index]);

Otros consejos

JSFIDDLE

var array_of_numbers = [5,4,3,2,1,0],
    swap = function(array,a,b){var tmp=array[a];array[a]=array[b];array[b]=tmp;};
swap(array_of_numbers,0,4);
// array_of_numbers now is [1,4,3,2,5,0]

Or you can do add the function to the Array.prototype:

JSFIDDLE

Array.prototype.swap = function(a,b){ var tmp=this[a];this[a]=this[b];this[b]=tmp;};
var array_of_numbers = [5,4,3,2,1,0];
array_of_numbers.swap(0,4);
// array_of_numbers now is [1,4,3,2,5,0]
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top