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? Commented Jul 9, 2015 at 12:38
  • Yes, it's populated by unique file-names Commented Jul 9, 2015 at 12:39
  • @idleberg Is it okay if your original array is tampered in the process? Commented Jul 9, 2015 at 12:50
  • @thefourtheye yeah, that's fine Commented 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'));

Sign up to request clarification or add additional context in comments.

1 Comment

it will modify the original array, is it ok?
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));
}

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.