Home > Software engineering >  Sorting in Javascript based on 2 parameters
Sorting in Javascript based on 2 parameters

Time:03-03

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.

CodePudding user response:

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.

CodePudding user response:

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