Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fastest way to move the last element to second item in the array

Tags:

javascript

I have the array of arrayData = ['abc', 'bcd', 'cdf', 'dfg']

Is there the fastest way to move the the item to the top of array?

So the final result should be arrayData = ['abc', 'dfg' , 'bcd', 'cdf' ]

like image 929
Kim Avatar asked Dec 07 '22 23:12

Kim


1 Answers

Simplest to move from end of array to second position is:

arrayData.splice(1, 0, arrayData.pop())

splice takes two fixed arguments, the index to begin at and the number of elements to delete, then variable arguments for the elements to insert at the same position. So this starts at index 1, deletes 0 elements, and inserts the element it popped off the end. I can't swear it's always fastest (implementations could easily differ by browser), but it avoids constructing any intermediate arrays, and is as explicit/direct as possible.

If the goal is to move from end to beginning (your question description says move to the "top"), then it's even simpler:

arrayData.unshift(arrayData.pop())

where you just pop off the right and "unshift" the resulting value onto the left side.

like image 73
ShadowRanger Avatar answered May 12 '23 10:05

ShadowRanger