-8

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"]?

Choylton B. Higginbottom
  • 2,236
  • 3
  • 24
  • 34

2 Answers2

0
let a = ["a", "b", "c"]

a.unshift(a.pop())
Choylton B. Higginbottom
  • 2,236
  • 3
  • 24
  • 34
  • 1
    While this code snippet may solve the problem, it doesn't explain why or how it answers the question. Please [include an explanation for your code](//meta.stackexchange.com/q/114762/269535), as that really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion. – Luca Kiebel Jan 28 '22 at 09:08
-1

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
junvar
  • 11,151
  • 2
  • 30
  • 46