3 回答
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;
})
);
TA贡献1744条经验 获得超4个赞
您可以按顺序比较两者:
accounts.sort((a, b) => a.bankType.localeCompare(b.bankType) || a.currency.localeCompare(b.currency) );
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);
添加回答
举报