javascript - 首先按数字中的给定属性对对象数组进行排序,然后是字母(数字具有子排序)

标签 javascript jquery arrays sorting

我知道如何按数字或字母排序,但不确定如何同时进行。

sessionStorage.cart
==> "[
{"id":1, "number":1, "other_attributes":"other_values"},
{"id":2, "number":2, "other_attributes":"other_values"},
{"id":"processing", "other_attributes":"other_values"},
{"id":2, "number":1, "other_attributes":"other_values"},
{"id":"deposit", "other_attributes":"other_values"}
]"

我想按 id 对购物车进行排序,适用以下条件:

  • 首先显示id为整数的所有项目
  • 然后显示所有 id 为字符串的项目
  • 其中id为整数,如果多个item具有相同的整数,则按number排序
  • 其中id为字符串,按字母顺序排序

上面例子的最终结果应该是(JSON解析后,设置回sessionStorage)

==> "[
{"id":1, "number":1, "other_attributes":"other_values"},
{"id":2, "number":1, "other_attributes":"other_values"},
{"id":2, "number":2, "other_attributes":"other_values"},
{"id":"deposit", "other_attributes":"other_values"},
{"id":"processing", "other_attributes":"other_values"},
]"

最佳答案

您可以使用 sort() 具有自定义排序功能

var arr = [{
  "id": 1,
  "number": 1,
  "other_attributes": "other_values"
}, {
  "id": 2,
  "number": 2,
  "other_attributes": "other_values"
}, {
  "id": "processing",
  "other_attributes": "other_values"
}, {
  "id": 2,
  "number": 1,
  "other_attributes": "other_values"
}, {
  "id": "deposit",
  "other_attributes": "other_values"
}];

arr = arr.sort(function(a, b) {
  // check both id's are number
  if (typeof a.id == 'number' && typeof b.id == 'number') {
    // check both are equal
    if (a.id == b.id)
      // if equal sort based on `number`
      return a.numer - b.number
    // else sort based on id  
    return a.id - b.id
    // check first one is number
  } else if (typeof a.id == 'number')
    // since number have higher sort order return -1
    return -1;
  // check second one is number
  else if (typeof b.id == 'number')
    // since string have lower sort order return 1
    return 1;
  // in case both are string
  else {
    // return based on string comaprison
    if (a.id > b.id)
      return 1;
    else if (a.id < b.id)
      return -1
    return 0;
  }
});

document.write('<pre>' + JSON.stringify(arr, null, 3) + '</pre>');

关于javascript - 首先按数字中的给定属性对对象数组进行排序,然后是字母(数字具有子排序),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36231920/

相关文章:

javascript - 在哪里存储 JWT Client Credentials Grant

javascript - Jquery nextAll 和克隆不保留数据属性

java - 我如何将 JsonArray 从 jsp 解析为 Javascript

java - Java 新手 - 为什么这不能编译?

python - 计算 1000 个数组的统计数据

python - 沿轴平滑数组

javascript - Angular 深度比较除特定属性外的对象

javascript - window.location 未更新

jquery - 我想使用 ajax 重定向到下一页,但它可以工作

javascript - 包含DIV的显示宽度