Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript sort array double sort

Tags:

javascript

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.

like image 223
frenchie Avatar asked May 01 '12 20:05

frenchie


1 Answers

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.

like image 173
Shiplu Mokaddim Avatar answered Oct 26 '22 03:10

Shiplu Mokaddim