1

I am trying to sort the items in alphbatical order. However, I also want to sort item type as well.

For example:

I want

  type     sortValue

blockItem   a test1
blockItem   a test2
blockItem   b test3
imageItem   a image
imageItem   b image
imageItem   c image
imageItem   s image
textItem    a text
textItem    b text
textItem    c text

My code would do things like this.

  type     sortValue

blockItem   a test1
blockItem   a test2
imageItem   a image
textItem    a text
blockItem   b test3
imageItem   b image
textItem    b text
imageItem   c image
textItem    c text
imageItem   s image

my sort function

array contains type and sortvalue

array=array.sort(sortFunction);

function sortFunction(groupA, groupB) {

    if (groupA.sortValue > groupB.sortValue) {
        return 1;
    } else if (groupA.sortValue < groupB.sortValue) {
        return -1;
    }

    return 0;
}

It only sort the text but not the type. I was wondering if there are anyways to do this. Thanks so much!

FlyingCat
  • 14,036
  • 36
  • 119
  • 198

2 Answers2

3

Use the second key to compare if the first were equal:

function sortFunction(a, b) {
    if (a.key1 > b.key1) {
        return +1;
    } else if (a.key1 < b.key1) {
        return -1;
    } else if (a.key2 > b.key2) {
        return +1;
    } else if (a.key2 < b.key2) {
        return -1;
    } else 
    ...
    } else if (a.keyN > b.keyN) {
        return +1;
    } else if (a.keyN < b.keyN) {
        return -1;
    } else {
       return 0;
    }   
}

Or, for better readability:

function sortFunction(a, b) {
    if (a.key1 > b.key1) {
        return +1;
    } else if (a.key1 < b.key1) {
        return -1;
    }

    if (a.key2 > b.key2) {
        return +1;
    } else if (a.key2 < b.key2) {
        return -1;
    }
    ...

    if (a.keyN > b.keyN) {
        return +1;
    } else if (a.keyN < b.keyN) {
        return -1;
    }

    return 0;
}
Kijewski
  • 25,517
  • 12
  • 101
  • 143
  • 3
    Nice. Btw, you can shorten it to `return (a.key1>b.key1)-(a.key1b.key2)-(a.key2b.keyN)-(a.keyN b.keyN);` – Bergi Feb 22 '13 at 00:04
2
if (groupA.type == groupB.type) {
    /* your code */
}
else if (groupA.type > groupB.type) {
    return 1;
}
else if (groupA.type < groupB.type) {
    return -1;
}

return 0;
Explosion Pills
  • 188,624
  • 52
  • 326
  • 405