DEV Community

Discussion on: How to shift array position in vanilla JavaScript

Collapse
 
lexlohr profile image
Alex Lohr

Why not use a really simple solution with plain ES5?

function lastToFirst(array) {
  const result = array.slice(0);
  result.unshift(result.pop());
  return result;
}
Collapse
 
michaeljota profile image
Michael De Abreu

This was literally my first thought when I was reading the problem.

Collapse
 
link2twenty profile image
Andrew Bone

I agree this is readable.

If you handed this to a new developer and asked them what it did they might be lost for a little while.

const lastToFirst = _ => [_.pop(), ..._];
Collapse
 
lexlohr profile image
Alex Lohr

Also, that would change the original array, which is not the intended functionality.

Thread Thread
 
link2twenty profile image
Andrew Bone • Edited

Good point, you'd have to do something like

const lastToFirst = _ => {const $ = _.slice(); return [$.pop(), ...$]};

which is even more convoluted.

Thread Thread
 
lexlohr profile image
Alex Lohr

How about const lastToFirst = _ => ($ => [$.pop(), ...$])(_.slice()) as even more convoluted example?

Thread Thread
 
link2twenty profile image
Andrew Bone

Yikes...

I kinda love it.

Collapse
 
somedood profile image
Basti Ortiz

I mean it would be ES5 if const was var. 😂

Anyway, I like how concise it is. Three lines of code sure does look more satisfying than whatever I did, despite their similarities.