Home > Net >  I want to sort list containing string combination of numbers and alphabets
I want to sort list containing string combination of numbers and alphabets

Time:07-29

I want to sort list containing strings combination of numbers and alphabets.

For example If list contains [A2, 1, A, 2, AAA, AA2, B, A1, A3, AA, AA1, 0, AC, A31, AC, AB,...]

Then it should be sort like: [0, 1, 2, 3 , A, A1, A2, A3, A31, AA, AA1, AA2, AAA, AB, AC, B...]

Currently doing something like below

function sortStrings(a: any, b: any) {
let idA: string = a.cassetteName.toLocaleUpperCase();
let idB: string = b.cassetteName.toLocaleUpperCase();
if(idA.includes('*')){
  return idA > idB ? 1 : -1;
}else{
  //return idA.localeCompare(idB, 'en', { numeric: true })
  return idA.localeCompare(idB, undefined, {
    numeric: true,
    sensitivity: 'base'
  })
}

}

stringList.Sort(sortStrings);

What will be the solution. Thanks.

CodePudding user response:

You could take standard sort without callback.

const
    data = ['A2', '1', 'A', '2', 'AAA', 'AA2', 'B', 'A1', 'A3', 'AA', 'AA1', '0', 'AC', 'A31', 'AC', 'AB'];

console.log(...data.sort());

  • Related