简体   繁体   English

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

[英]JavaScript sort array of objects on multiple properties by specific constant values

Given an object like:给定一个对象,如:

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 },
];

How do I sort by the objects properties in the array where bankType of "Checkings" are sorted first then currency of "CAD" accounts are sorted next to achieve the following result below?如何按数组中的对象属性进行排序,其中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 },
];

The problem isn't about sorting it alphabetically using the built-in localeCompare function, the problem lies in having to sort by specific constant value of Checking first then by CAD second.问题不在于使用内置的localeCompare函数按字母顺序排序,问题在于必须localeCompare Checking的特定常量值排序,然后再按CAD排序。

You can just compare the two in order:您可以按顺序比较两者:

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

With a point system有积分系统

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; }) );

Using Array.prototype.sort and String.prototype.localeCompare , you can sort them.使用Array.prototype.sortString.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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM