[英]JavaScript sort array of objects on multiple properties by specific constant values
给定一个对象,如:
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"
bankType
进行排序,然后对"CAD"
帐户的currency
进行排序,以实现以下结果?
// 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
函数按字母顺序排序,问题在于必须localeCompare
Checking
的特定常量值排序,然后再按CAD
排序。
您可以按顺序比较两者:
accounts.sort((a, b) =>
a.bankType.localeCompare(b.bankType) || a.currency.localeCompare(b.currency)
);
有积分系统
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; }) );
使用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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.