Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

sorting javascript array on custom string condition

I have an array in the following format.

const arr = [{name:'11'},{name:'10'},{name:'9'},{name:'8'},{name:'7'}
{name:'6'},{name:'5'},{name:'4'},{name:'3'},{name:'2'},{name:'1'}
{name:'UN'},{name:'PG'},{name:'LN'},
{name:'12'},{name:'13'}]

I can sort it to get an output like below.

arr.sort((x, y)=> {
        if(x.name == 'LN' || x.name=='UN' || x.name== 'PG' || (parseInt(x.name)<parseInt(y.name))) {
          return -1;
        }
        return 0;
      })

Current Output : simplified for easy visualization

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

[LN,PG,UN,1,2,3,4,5,6,7,8,9,10,11,12,13]

I want PG to come after UN. Should do a swap like below after sorting or can it be done in the sort function it self?

[arr[1], arr[2]] = [arr[2],arr[1]]

Expected Output : simplified for easy visualization

[LN,UN,PG,1,2,3,4,5,6,7,8,9,10,11,12,13]

>Solution :

One way is to give the name a rank,

Assuming your numbers are always positive, a really simple way to rank is use a lookup for the text, making them less than 0. If new name types appear in the future it’s just a case of updating the rank lookup. You can then sort on this rank function.

eg..

const arr = [{name:'11'},{name:'10'},{name:'9'},{name:'8'},{name:'7'},
{name:'6'},{name:'5'},{name:'4'},{name:'3'},{name:'2'},{name:'1'},
{name:'UN'},{name:'PG'},{name:'LN'},
{name:'12'},{name:'13'}];

const ranks = {
  LN: -3,
  UN: -2,
  PG: -1
}

function rank(n) {
  if (ranks[n]) return ranks[n]
  else return Number(n);
}

arr.sort((a,b) => {
  return rank(a.name) - rank(b.name);
});

console.log(arr);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading