8

I have an array looking like this:

arr = ['a', 'b', 'c', 'd', 'e', 'f'];

How can I shift its values while maintaining the order. For instance, I'd like to start it with 'd':

new_arr = shiftArray(arr, 'd'); // => ['d', 'e', 'f', 'a', 'b', 'c']
4
  • Are you sure your array is always unique?
    – axelduch
    Jul 9, 2015 at 12:38
  • Yes, it's populated by unique file-names
    – idleberg
    Jul 9, 2015 at 12:39
  • @idleberg Is it okay if your original array is tampered in the process? Jul 9, 2015 at 12:50
  • @thefourtheye yeah, that's fine
    – idleberg
    Jul 9, 2015 at 13:29

2 Answers 2

9

You can do something like this

function shiftArray(arr, target){ 
  return arr.concat(arr.splice(0,arr.indexOf(target)));
}

var arr = ['a', 'b', 'c', 'd', 'e', 'f'];
function shiftArray(arr, target){ 
  return arr.concat(arr.splice(0,arr.indexOf(target)));
}
alert(shiftArray(arr, 'd'));

1
  • 1
    it will modify the original array, is it ok?
    – axelduch
    Jul 9, 2015 at 12:41
5

This will not modify the original array, also I recommend you rename the function

function rotateArrayAround(array, pivotNeedle) {
   var pivot = array.indexOf(pivotNeedle);   
   return array.slice(pivot).concat(array.slice(0, pivot));
}
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.