Javascript sort array double sort

I have an array of MyArrayOfItemsobjects Itemwith 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 is sorted by ContainerID, and then by ItemNamealphabetically.

I have a custom sort function that still 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 sort by ItemName?

Thank.

+5
source share
2 answers

Use the String.localeCompare function . And use it when ContainerIDout aand bequal.

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 set the sort order, you can always put -before any expression return.

+6
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;
  }
}
+4

All Articles