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

14
  • 1
    I don't think the word "sort" is appropriate here, as "sorting" means "reordering". Rotate maybe?
    – Pointy
    Jan 11, 2015 at 17:16
  • Yep "reordering" sounds better
    – Ben
    Jan 11, 2015 at 17:16
  • start from the index a go the end after that restart from 0 index and go to the first starting index. Try it yourself... You can use two loops for that...
    – EugenSunic
    Jan 11, 2015 at 17:17
  • but you got the idea right ?
    – Ben
    Jan 11, 2015 at 17:17
  • @esner_togo well I tried a lot that's why I'm asking here
    – Ben
    Jan 11, 2015 at 17:17

2 Answers 2

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

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.
 }

Not the answer you're looking for? Browse other questions tagged or ask your own question.