Home > Software design >  Sort the list of string in which some string begin with parentheses in javascript
Sort the list of string in which some string begin with parentheses in javascript

Time:10-05

I'm trying to order a list of string where some begin with parenthesis. I want to order in ascending way, but the string with the parenthesis should be at the end.

const items = 
      ['ABC - Desk 1 ', 
       'NDF - Desk 2 ' ,
       '(Busy) DEF - desk 3 ',
       '(Busy) Test desk ']

I trying with:

if(orderAsc){
    items.sort((item1, item2) =>  item1.localeCompare(item2));
} else {
   items.sort((item1, item2) => item2.localeCompare(item1));
}

but the result is

> "(Busy) DEF - desk 3 "
> "(Busy) Test desk "
> "ABC - Desk 1 "
> "NDF - Desk 2 "

else

> "NDF - Desk 2 "
> "ABC - Desk 1 "
> "(Busy) Test desk "
> "(Busy) DEF - desk 3 "

What I need is

'ABC - Desk 1 ', 
'NDF - Desk 2 ' ,
'(Busy) DEF - desk 3 ',
'(Busy) Test desk '

Where without parentheses are the firsts and after those with the parentheses.

CodePudding user response:

I wrote this function and it produces the exact output you're looking for.

const sortedItems = items.sort((a, b) => {
    const aBusy = a.includes('(Busy)');
    const bBusy = b.includes('(Busy)');
    if (aBusy && !bBusy) {
        return 1;
    }
    if (!aBusy && bBusy) {
        return -1;
    }
    return a.localeCompare(b);
});

Console output:

[
  'ABC - Desk 1 ',
  'NDF - Desk 2 ',
  '(Busy) DEF - desk 3 ',
  '(Busy) Test desk '
]

CodePudding user response:

You could do a temporary replacement character or string to ensure that the items go last in the array.

const items = ['(Busy) DEF - desk 3 ', 'NDF - Desk 2 ', '(Busy) Test desk ', 'ABC - Desk 1 ']
let sorted = items.map(m => m.replace("(", "ZZZ|")).sort((a, b) => a.localeCompare(b)).map(m => m.replace("ZZZ|", "("))
console.log(sorted)

  • Related