I have an array of objects. I want to move a selected object to the last position in the array. How do I do this in javascript or jquery?
Here is some code I have:
to move an element (of which you know the index) to the end of an array, do this:
array.push(array.splice(index, 1)[0]);
If you don't have the index, and only the element, then do this:
array.push(array.splice(array.indexOf(element), 1)[0]);
Example:
var arr = [1, 2, 6, 3, 4, 5];
arr.push(arr.splice(arr.indexOf(6), 1)[0]);
console.log(arr); // [1, 2, 3, 4, 5, 6]
NOTE:
this only works with Arrays (created with the
[ ... ]
syntax orArray()
) not with Objects (created with the{ ... }
syntax orObject()
)