6

I have an array MyArrayOfItems of Item objects with objects that look like this:

Item
{
  ContainerID: i, // int
  ContainerName: 'SomeName', // string
  ItemID: j, // int
  ItemName: 'SomeOtherName' // string
}

I want to sort this array so that it's sorted by ContainerID and then by ItemName alphabetically.

I have a custom sort function that so far looks like this:

function CustomSort(a, b) {

  Item1 = a['ContainerID'];
  Item2 = b['ContainerID'];

  return Item1 - Item2;
}

MyArrayOfItems.sort(CustomSort);

This sorts by ContainerID but how do I then sort by ItemName?

Thanks.

frenchie
  • 48,391
  • 102
  • 295
  • 498
  • possible duplicate of [Javascript sort array by two fields](http://stackoverflow.com/questions/6129952/javascript-sort-array-by-two-fields) – Felix Kling May 01 '12 at 20:23
  • @FelixKling: not really; I need it to sort alphabetically. – frenchie May 01 '12 at 20:25
  • So? You can easily compare stings with `` though I agree that `localCompare` is a better way. I thought the overall question was about how to sort by two properties, in which case it is clearly a duplicate. – Felix Kling May 01 '12 at 21:28

3 Answers3

6

Use String.localeCompare function. And use it when ContainerID of a and b are equal.

function CustomSort(a, b) {
  var Item1 = a['ContainerID'];
  var Item2 = b['ContainerID'];
  if(Item1 != Item2){
      return (Item1 - Item2);
  }
  else{
      return (a.ItemName.localeCompare(b.ItemName));
  }
}

To tweak the sorting order you can always put - in front of any return expression.

Shiplu Mokaddim
  • 54,465
  • 14
  • 131
  • 183
5
function CustomSort(a, b) {

  Item1 = a['ContainerID'];
  Item2 = b['ContainerID'];
  if(Item1 - Item2 !=0){
      return Item1 - Item2;
  }
  else{
      if (a.ItemName < b.ItemName)
         return -1;
      if (a.ItemName > b.ItemName)
         return 1;
      return 0;
  }
}
Rajat Singhal
  • 11,084
  • 5
  • 37
  • 55
0

A nice simplification of this is:

function CustomSort(a, b) {
  var Item1 = a['ContainerID'];
  var Item2 = b['ContainerID'];
  

 if(Item1 != Item2){
      return (Item1 - Item2);
  }
  else{
      return (a.ItemName.localeCompare(b.ItemName));
  }
}
Jonathan Tuzman
  • 8,961
  • 12
  • 53
  • 98