Swapping elements in an array of objects
11,384
Solution 1
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]);
Solution 2
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
:
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]
Author by
James Allingham
Updated on June 18, 2022Comments
-
James Allingham almost 2 years
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. -
MT0 over 10 yearshttp://jsperf.com/js-list-swap - Using splice is a lot slower than a temporary variable.
-
James Allingham over 10 yearsThanks very much! Worked perfectly!