3

Having the following array :

var arr = [a,b,c,d,e];

I'm struggling to get a clean function that sorts the array based on a specified index, keeping at the same time the original order

For example, sorting the array from index 3 (so here, from "d"), would give the following :

[d,e,a,b,c]

From index 2 :

[c,d,e,a,b]

etc...

It might be obvious for some but I can't make it in my mind

Help appreciated, thx in advance

* Edit *

Is a duplicate. Here is a good one.

https://stackoverflow.com/a/7861200/102133

Community
  • 1
  • 1
Ben
  • 4,449
  • 4
  • 44
  • 79

2 Answers2

3

var arr = ['a','b','c','d','e'];

function reorder(data, index) {
  return data.slice(index).concat(data.slice(0, index))
};

console.log(reorder(arr, 3));
console.log(reorder(arr, 2));
Oleksandr T.
  • 69,412
  • 16
  • 152
  • 136
1

This function will do your work

var reorder = function(arr,index){
    var start = arr.slice(index); // This will return me elements from a given index
    var end = arr.slice(0,index); // This will return me elements before a given index
    return start.concat(end); // Concat 2nd array to first and return the result.
 }
Mritunjay
  • 22,738
  • 6
  • 47
  • 66