DEV Community

Discussion on: How to shift array position in vanilla JavaScript

Collapse
 
somedood profile image
Basti Ortiz • Edited

I think this will do just fine.

function shiftArray(arr) {
  // Get the last element in the array
  const lastElement = arr[arr.length - 1];

  // Prepend the `lastElement` to the start of the array
  arr.unshift(lastElement);

  // Remove the duplicate element at the end of the array
  arr.pop();

  // Hooray! We party! 🎉
  return arr;
}

// Plop in `theList`
shiftArray(theList);