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' ]
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With