Home > OS >  Sort a strings array in ascending order with a word priority
Sort a strings array in ascending order with a word priority

Time:11-16

For the following array

[
  { name: '4K UHD', commentator: 'Ali' },
  { name: 'English 1 HD', commentator: 'Ahmed' },
  { name: 'English 3 HD', commentator: 'Ahmed' },
  { name: 'Premium 1 HD', commentator: 'Ali' },
  { name: 'Premium 2 HD', commentator: 'Ahmed' },
]

I want to sort it so that objects with a name of Premium (as the last two objects) comes first but also in ascending order.

The desired result is this

[
  { name: 'Premium 1 HD', commentator: 'Ali' },
  { name: 'Premium 2 HD', commentator: 'Ahmed' },
  { name: '4K UHD', commentator: 'Ali' },
  { name: 'English 1 HD', commentator: 'Ahmed' },
  { name: 'English 3 HD', commentator: 'Ahmed' },
]

// or like this
[
  { name: 'Premium 1 HD', commentator: 'Ali' },
  { name: 'Premium 2 HD', commentator: 'Ahmed' },
  { name: 'English 1 HD', commentator: 'Ahmed' },
  { name: 'English 3 HD', commentator: 'Ahmed' },
  { name: '4K UHD', commentator: 'Ali' },
]

CodePudding user response:

By creating a custom compare function

const cmp = (a, b) => {
    const pa = a.name.startsWith("Premium");
    const pb = b.name.startsWith("Premium");
    return 
        pa !== pb 
          // comparing Premium vs non-Premium, Premium "wins"
        ? (pa ? -1 : 1) 
          // everything else (i.e. Prem vs Prem or non-Prem vs non-Prem)
        : a.name.localeCompare(b.name); 
};

dataArray.sort(cmp);

You can ensure that all strings starting with Premium are moved to the top of the sort, while ensuring that the sort order is retained among the Premium and non-Premium "groups".

CodePudding user response:

Try Decending order:

array.sort((a, b) => a.name < b.name ? 1 : -1)
  • Related