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']
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']
Share
Improve this question
asked Jul 9, 2015 at 12:37
idlebergidleberg
12.9k10 gold badges45 silver badges71 bronze badges
4
- Are you sure your array is always unique? – axelduch Commented Jul 9, 2015 at 12:38
- Yes, it's populated by unique file-names – idleberg Commented Jul 9, 2015 at 12:39
- @idleberg Is it okay if your original array is tampered in the process? – thefourtheye Commented Jul 9, 2015 at 12:50
- @thefourtheye yeah, that's fine – idleberg Commented Jul 9, 2015 at 13:29
2 Answers
Reset to default 9You 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'));
This will not modify the original array, also I remend you rename the function
function rotateArrayAround(array, pivotNeedle) {
var pivot = array.indexOf(pivotNeedle);
return array.slice(pivot).concat(array.slice(0, pivot));
}
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744281735a4566602.html
评论列表(0条)