How can I move the last item in an array to the start?
So, for example, I have the array ["a", "b", "c"]
. How do I make it ["c", "a", "b"]
?
How can I move the last item in an array to the start?
So, for example, I have the array ["a", "b", "c"]
. How do I make it ["c", "a", "b"]
?
let a = ["a", "b", "c"]
a.unshift(a.pop())
Array.slice()
is a good start, and it doesn't modify the original array. Here's a small algorithm using `Array.slice() and supporting wrap around:
let rotatingSlice = (a, start, end) => {
if (start < 0 && end > a.length)
return a.slice(start).concat(a.slice(0, end));
if (start < 0)
return a.slice(start).concat(a.slice(0, end));
else if (end > a.length)
return a.slice(start).concat(a.slice(0, end % a.length));
else
return a.slice(start, end);
};
let array = [0,1,2,3,4,5,6,7];
console.log(rotatingSlice(array, 0, 3)) // 1st 3 elements
console.log(rotatingSlice(array, -3, 0)) // last 3 elements
console.log(rotatingSlice(array, -3, 3)) // last 3 and 1st 3 elements
console.log(rotatingSlice(array, 4, 4 + array.length)) // the array starting at the middle