-2

I have a use case wherein I want to sort the below given array

const account = [
{
    currency: "CNY",
    available_balance: 1000
}, 
{
    currency: "HKD",
    available_balance: 100
}, 
{
    currency: "CNY",
    available_balance: 200
}, 
{
    currency: "HKD",
    available_balance: 1500
}];

Now I have to sort it as follows,

const output = [
{
    currency: "CNY",
    available_balance: 1000
},
{
    currency: "CNY",
    available_balance: 200
},
{
    currency: "HKD",
    available_balance: 1500
},
{
    currency: "HKD",
    available_balance: 100
}];

The one with higher balance in CNY is first followed by the lower balances of CNY. After that I want to display HKD with higher balance first.

I was able to sort according to the available_balance but with not currency.

sortedAccount = account.sort((a, b) => {
return b.available_balance - a.available_balance;
});
console.log(sortedAccount);

Please help :) Thank you.

  • Does this answer your question? [How to sort an array of objects by multiple fields?](https://stackoverflow.com/questions/6913512/how-to-sort-an-array-of-objects-by-multiple-fields) – pilchard Mar 02 '22 at 11:14

2 Answers2

1

The general pattern for multi-field sorts is:

sortedAccount = account.sort((a, b) => {
  let res = a.currency.localeCompare(b.currency)
  if (res) return res
  res = b.available_balance - a.available_balance
  return res
});

You keep letting the result fall through to the next condition if '0'.

This solution will sort on language ascending and then balance descending.

Steven Spungin
  • 27,002
  • 5
  • 88
  • 78
0

You can combine this with an || expression:

sortedAccount = account.sort((a, b) => {
  return a.currency.localeCompare(b.currency) ||    // Ascending currency
         b.available_balance - a.available_balance; // Descending balance
});
trincot
  • 317,000
  • 35
  • 244
  • 286