Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shift array by value, keep sorting in order

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']
like image 430
idleberg Avatar asked Jul 09 '15 12:07

idleberg


2 Answers

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'));
like image 139
Dhiraj Avatar answered Sep 19 '22 21:09

Dhiraj


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));
}
like image 20
axelduch Avatar answered Sep 20 '22 21:09

axelduch