javascript - Shift array by value, keep sorting in order - Stack Overflow

I have an array looking like this:arr = ['a', 'b', 'c', 'd', &#

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
Add a ment  | 

2 Answers 2

Reset to default 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'));

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条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信