1

My issue is very simple to explain, but figuring out the most efficient way of doing it is proving difficult.

I am trying to reorder an array starting at a particular index in the array.

What I have:

var array = [1,2,3,4,5];

What I want:

array = [3,4,5,1,2];

What I've done:

var array = [1,2,3,4,5];
var arr1 = array.slice(array.indexOf(3), array.length);
var arr2 = array.slice(0, array.indexOf(3));

arr1.push(arr2);

var newArray = arr1.join(); // [3,4,5,1,2];

As you can see, there is quite a bit going on for what is seemingly a simple task. If you have any suggestions on how to improve this I'd be grateful. Either vanilla JS or Underscore/Lodash is fine.

abyrne85
  • 1,280
  • 11
  • 28

4 Answers4

3

How about one line:

var array = array.slice(2, array.length).concat(array.slice(0, 2));

DEMO

Andy
  • 39,764
  • 8
  • 53
  • 80
1

This will not get you a flat array at the end :

arr1.push(arr2);
var newArray = arr1.join();

what you need to do is to call the method Array.prototype.concat

var newArray = arr1.concat(arr2);
Khalid
  • 4,392
  • 5
  • 23
  • 50
1

More functional-like approach:

var reorder = function(array, index) {
  return _.flatten(_.partition(array, function(v, i) {return i < index}).reverse())
};
reorder([1,2,3,4,5], 3);

Or instead of _.flatten, you can use _.union.apply(null, ...).

andrusieczko
  • 2,794
  • 10
  • 22
1

A nice easy way with underscore is to use the first and rest functions and concatenate the results. Here's a mixin that does just that:

    _.mixin( { reorder: function(list, index){
        return _.rest(list,index).concat(_.first(list,index));
    }});

    var result = _.reorder(array, 3)
Gruff Bunny
  • 26,318
  • 10
  • 66
  • 56