简体   繁体   中英

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?

// 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.

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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