亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

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 關注
  • 178 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號