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

给定一个像这样的对象:


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第二个的特定常量值进行排序。


holdtom
浏览 274回答 3
3回答

慕容708150

有积分系统Checking = 2CAD = 1console.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;        }));

慕无忌1623718

您可以按顺序比较两者:accounts.sort((a, b) =>     a.bankType.localeCompare(b.bankType) || a.currency.localeCompare(b.currency) );

手掌心

使用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);
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript