5

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' ]

zangw
  • 43,869
  • 19
  • 177
  • 214
Kim
  • 315
  • 4
  • 7
  • 13

3 Answers3

14

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.

ShadowRanger
  • 143,180
  • 12
  • 188
  • 271
2

If you use native methods like unshift or splice, it will rebuild the entire array. The fastest way is switching the necessary values using a temporary variable. This way the operation will be O(1) -> constant time, instead O(N) -> linear time.

var temp = arrayData[0];
arrayData[0] = arrayData[arrayData.length -1];
arrayData[arrayData.length -1] = temp;
Elvio Cavalcante
  • 476
  • 5
  • 10
0

Use the splice method of the Array object, I think your question has already been answered. On stackoverflow see: How to insert an item into an array at a specific index? For further details and examples see: http://ariya.ofilabs.com/2014/02/javascript-array-slice-vs-splice.html

Community
  • 1
  • 1
Arif Burhan
  • 507
  • 4
  • 12