最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript sort array double sort - Stack Overflow

programmeradmin4浏览0评论

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.

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.

Share Improve this question asked May 1, 2012 at 20:21 frenchiefrenchie 52k117 gold badges319 silver badges526 bronze badges 3
  • possible duplicate of Javascript sort array by two fields – Felix Kling Commented May 1, 2012 at 20:23
  • @FelixKling: not really; I need it to sort alphabetically. – frenchie Commented May 1, 2012 at 20:25
  • So? You can easily pare stings with < and > 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 Commented May 1, 2012 at 21:28
Add a ment  | 

3 Answers 3

Reset to default 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.

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;
  }
}

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));
  }
}
发布评论

评论列表(0)

  1. 暂无评论