【问题标题】:Sorting an array of objects in ascending order based on two keys having different datatypes根据具有不同数据类型的两个键对对象数组进行升序排序
【发布时间】:2019-11-28 06:38:24
【问题描述】:

我想根据两个属性对数组进行升序排序。

我有以下看起来像的数据数组

[
  {
    id: 1,
    name: 'ABP',
    code: 1460,
    subCode: '0010'
  },
  {
    id: 2,
    name: 'GKY',
    code: 1460,
    subCode: '0030'
  },
  {
    id: 3,
    name: 'CPT',
    code: 1410,
    subCode: '0070'
  },
  {
    id: 4,
    name: 'KLB',
    code: 1470,
    subCode: '0050'
  },
  {
    id: 5,
    name: 'POL',
    code: 1430,
    subCode: '0050'
  },
  {
    id: 6,
    name: 'FVB',
    code: 1410,
    subCode: '0050'
  },
]

我想把它排序

[
  {
    id: 6,
    name: 'FVB',
    code: 1410,
    subCode: '0050'
  },
  {
    id: 3,
    name: 'CPT',
    code: 1410,
    subCode: '0070'
  },
  {
    id: 5,
    name: 'POL',
    code: 1430,
    subCode: '0050'
  },
  {
    id: 1,
    name: 'ABP',
    code: 1460,
    subCode: '0010'
  },
  {
    id: 2,
    name: 'GKY',
    code: 1460,
    subCode: '0030'
  },
  {
    id: 4,
    name: 'KLB',
    code: 1470,
    subCode: '0050'
  },
]

我想根据code 属性对数组进行升序排序,如果多个项目存在相同的code,那么我想根据code 属性的subCode 对其进行排序。

我在这里面临的问题是,subCode 是字符串,code 是数字。 我尝试过使用array.sort,也尝试使用整数解析subCode,但它返回了我不理解的不同数字。

【问题讨论】:

  • 您用来解析子代码的代码在哪里,因为有不同的方式将字符串解析为数字...请粘贴该代码
  • 到目前为止你编写了哪些代码来实现这一目标?
  • 这可能就是你要找的东西:stackoverflow.com/q/6129952/12407377
  • Try this 但使用 underscore.js - 我认为你会喜欢的 javascript 库。
  • @SriVenkataPavanKumarMHS 我尝试使用 parseInt('0030') 返回 30。不知道为什么

标签: javascript arrays sorting


【解决方案1】:

您可以减去 compareFunction 中的代码属性。如果ab 具有相同的code 属性,则|| 运算符将减去subCode 属性。 - 运算符会将字符串强制转换为数字,并返回一个数值。

const input=[{id:1,name:"ABP",code:1460,subCode:"0010"},{id:2,name:"GKY",code:1460,subCode:"0030"},{id:3,name:"CPT",code:1410,subCode:"0070"},{id:4,name:"KLB",code:1470,subCode:"0050"},{id:5,name:"POL",code:1430,subCode:"0050"},{id:6,name:"FVB",code:1410,subCode:"0050"},];

input.sort((a, b) => a.code - b.code || a.subCode - b.subCode)

console.log(input)

【讨论】:

  • @MarkMeyer 由于减法,他们将被强制转换为数字。 "0030" - "0010" === 20
  • 对。我的头在python中。 +1。
【解决方案2】:

当您想将字符串值作为数字值比较时(这里是subCode),您需要先转换为数字来比较它们

见下面的代码。

Ary.sort(function (obj1, obj2) {
  if (obj1.code === obj2.code) {
    return Number(obj1.subCode) - Number(obj2.subCode)
  } else {
    return obj1.code - obj2.code
  }
})

我假设code 的值总是数字。

【讨论】:

    猜你喜欢
    • 2021-09-22
    • 1970-01-01
    • 1970-01-01
    • 2023-02-24
    • 2015-01-03
    • 2018-12-27
    • 2017-09-29
    • 2011-04-05
    • 1970-01-01
    相关资源
    最近更新 更多