Question

Using Javascript, I want to sort an array of integer, but instead of starting at 0, I would like to be able to specify the first item in the array. For example, using this array as a starting point:

var array = [4, 0, 1, 2, 5, 8, 7, 3, 6];

If I want to re-order but start at 3, with the end result:

var array = [3, 4, 5, 6, 7, 8, 0, 1, 2];

Start at 8 would look like this:

var array = [8, 0, 1, 2, 3, 4, 5, 6, 7];

Start at 0 would look like this (default sort):

var array = [0, 1, 2, 3, 4, 5, 6, 7, 8];

Any idea how I can do this? Thanks.

Was it helpful?

Solution

This should do it:

array.sort(function(a, b) {
   return (a<2) - (b<2) || a - b;
});

The first condition returns 1 or -1 depending on whether a or b are smaller than 2, or 0 if both are on the same "side" of 2, in which case the second (standard number) comparison takes place.

OTHER TIPS

What about this ?

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

var startNumber = 2;
var test = array.sort(function(a, b) {
    if(b < startNumber) {
        return -1;
    } else if(a < startNumber) {
        return 1;
    } else {
       return a - b;
    }
});

// test == [2, 3, 4, 5, 0, 1]

I'm not quite sure what you are trying to achieve, because in your original array 0 and 1 are already sorted.
Assuming that you want to sort the entire array and then shift the array to put first two elements to the end, you can use this code:

var array = [3, 4, 0, 1, 2, 5];
array = array.sort();
i = array.indexOf(2);
move = array.splice(0, i);
array.splice(array.length, 0, move);
alert(array);

Demo is here.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top