-1

let's say I have this array of number in reverse order:

var days = [6, 5, 4, 3, 2, 1, 0];

and I have this variable:

var startingDay = 4;

How can I sort the array so that the array is like this

console.log(days == [4, 3, 2, 1, 0, 6, 5]);
>> true

??

Thanks!

Dan Mantyla
  • 1,840
  • 1
  • 22
  • 33

1 Answers1

-1

You can rotate the array by slicing and concatenating the two parts.

var days = [6, 5, 4, 3, 2, 1, 0];
var day = 4;
var idx = days.indexOf(day);
var res = days.slice(idx).concat(days.slice(0, idx));
console.log(res);

You can also use unshift and splice to modify the array in-place.

var days = [6, 5, 4, 3, 2, 1, 0];
var day = 4;
days.unshift(...days.splice(days.indexOf(day), days.length));
console.log(days);
Unmitigated
  • 76,500
  • 11
  • 62
  • 80