'Sorting in Javascript based on 2 parameters

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.



Solution 1:[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.

Solution 2:[2]

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2