Move item in array to last position
Moving the first element of an array to the end of the same array
var a = [5,1,2,3,4];
a.push(a.shift());
console.log(a); // [1,2,3,4,5]
or this way
var a = [5,1,2,3,4];
var b = a.shift();
a[a.length] = b;
console.log(a); // [1,2,3,4,5]
Moving any element of an array to any position in the same array
// move element '5' (index = 2) to the end (index = 4)
var a = [1, 2, 5, 4, 3];
a.splice(4,0,a.splice(2,1)[0]);
console.log(a); // [1, 2, 4, 3, 5]
or it could be converted to a prototype as well, like this where x
represents the current position of element while y
represents the new position in array
var a = [1, 2, 5, 4, 3];
Array.prototype.move = function(x, y){
this.splice(y, 0, this.splice(x, 1)[0]);
return this;
};
a.move(2,4);
console.log(a); // ["1", "2", "4", "3", "5"]
Answer to the @jkalandarov comment
function moveToTheEnd(arr, word){
arr.map((elem, index) => {
if(elem.toLowerCase() === word.toLowerCase()){
arr.splice(index, 1);
arr.push(elem);
}
})
return arr;
}
console.log(moveToTheEnd(["Banana", "Orange", "Apple", "Mango", "Lemon"],"Orange"));
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()
)