为了账号安全,请及时绑定邮箱和手机立即绑定

JavaScript 按特定常量值对多个属性上的对象数组进行排序

JavaScript 按特定常量值对多个属性上的对象数组进行排序

holdtom 2023-07-29 15:50:35
给定一个像这样的对象:accounts = [  { bankType: "Checking", currency: "USD", amount: 123.45 },  { bankType: "Saving", currency: "CAD", amount: 1.95 },  { bankType: "Saving", currency: "USD", amount: 23.31 },  { bankType: "Checking", currency: "CAD", amount: 1953.1 },];如何按数组中的对象属性进行排序,其中bankType先"Checkings"排序,然后再排序currency帐户"CAD",以获得下面的结果?// Sorted array of objects result[  { bankType: "Checking", currency: "CAD", amount: 1953.1 },  { bankType: "Checking", currency: "USD", amount: 123.45 },  { bankType: "Saving", currency: "CAD", amount: 1.95 },  { bankType: "Saving", currency: "USD", amount: 23.31 },];问题不在于使用内置localeCompare函数按字母顺序对其进行排序,问题在于必须按Checking第一个然后按CAD第二个的特定常量值进行排序。
查看完整描述

3 回答

?
慕容708150

TA贡献1831条经验 获得超4个赞

有积分系统


Checking = 2


CAD = 1

console.log(

    [

        { bankType: "Checking", currency: "USD", amount: 123.45 },

        { bankType: "Saving", currency: "CAD", amount: 1.95 },

        { bankType: "Saving", currency: "USD", amount: 23.31 },

        { bankType: "Checking", currency: "CAD", amount: 1953.1 },

    ]

        .sort((a, b) => {

            const pointsA = (a.bankType === "Checking" ? 2 : 0) + (a.currency === "CAD" ? 1 : 0);

            const pointsB = (b.bankType === "Checking" ? 2 : 0) + (b.currency === "CAD" ? 1 : 0);


            return pointsB - pointsA;

        })

);


查看完整回答
反对 回复 2023-07-29
?
慕无忌1623718

TA贡献1744条经验 获得超4个赞

您可以按顺序比较两者:

accounts.sort((a, b) =>
    a.bankType.localeCompare(b.bankType) || a.currency.localeCompare(b.currency)
);


查看完整回答
反对 回复 2023-07-29
?
手掌心

TA贡献1942条经验 获得超3个赞

使用Array.prototype.sort和String.prototype.localeCompare,您可以对它们进行排序。


const accounts = [

  { bankType: "Checking", currency: "USD", amount: 123.45 },

  { bankType: "Saving", currency: "CAD", amount: 1.95 },

  { bankType: "Saving", currency: "USD", amount: 23.31 },

  { bankType: "Checking", currency: "CAD", amount: 1953.1 },

];


const output = accounts.sort((a, b) => {

  const bankCompare = a.bankType.localeCompare(b.bankType);

  if (bankCompare === 0) {

    return a.currency.localeCompare(b.currency);

  }

  return bankCompare;

});

console.log(output);


查看完整回答
反对 回复 2023-07-29
  • 3 回答
  • 0 关注
  • 133 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信