0

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.

1
  • 1
    What do you mean? An ordering does not "start" somewhere. Do you want to sort the array and then rotate it until the 2 is up front? Commented May 14, 2014 at 10:40

3 Answers 3

3

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.

Sign up to request clarification or add additional context in comments.

4 Comments

Could you explain what (a<2) or (b<2) would return when a or b is e.g. 5? At first I thought it would return true or false but that wouldn't make sense as you're calculating with the returned value afterwards? Thanks!
@codezombie: You can calculate with the booleans, they will be casted to 0/1 when being subtracted.
Thanks for your answer! Didn't know that so far! :-) But if (a<2) and (b<2) are both true, it would be 0 - 0 which yields 0 and equals true, wouldn't it? In that case, why is the second statement used instead of returning true? @Bergi
0 evaluates to false in javascript.
0

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]

1 Comment

Notice that this will leave 0 and 1 unsorted
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.