0

I am trying to reorder an array by two conditions. Making sure that Pos 10 goes after single digits and that it follows a specific order after that.

I tried to give priority to the string that includes first but then if I want to order alphanumerically it resets A to the top. How could I optain the expected result?

const arr = [
  'Pos 10 second',
  'Pos 10 A third',
  'Pos 10 first',
  'Pos 1 second',
  'Pos 1 A third',
  'Pos 1 first',
  'Pos 2 second',
  'Pos 2 A third',
  'Pos 2 first',
]

const res = arr.sort((a, b) => {
  if (a.includes('first')) {
    return -1
  } else {
    return 1
  }
  
}).sort((a, b) => a.localeCompare(b, 'en', { numeric: true}))

console.log(res)

/* Expected output
[
  'Pos 1 first',
  'Pos 1 second',
  'Pos 1 A third',
  'Pos 2 first',
  'Pos 2 second',
  'Pos 2 A third',
  'Pos 10 first',
  'Pos 10 second',
  'Pos 10 A third'
] */
Álvaro
  • 2,255
  • 1
  • 22
  • 48
  • https://stackoverflow.com/questions/2802341/javascript-natural-sort-of-alphanumerical-strings – HDM91 Sep 09 '21 at 10:07
  • you need to keep a list of priority of words and give them a number and use that in your sort algorithm – HDM91 Sep 09 '21 at 10:17
  • @HDM91 I know but how to do both, order by condition and by localcompare, can you reproduce the expected results? – Álvaro Sep 09 '21 at 10:27
  • how about moving locale compare inside first sort ? – HDM91 Sep 09 '21 at 10:34

1 Answers1

1

For the second sort use match on numbers within the string value, converted to Number.

const sorted = [
    'Pos 10 second',
    'Pos 10 A third',
    'Pos 10 first',
    'Pos 1 second',
    'Pos 1 A third',
    'Pos 1 first',
    'Pos 2 second',
    'Pos 2 A third',
    'Pos 2 first',
  ]
  .sort((a, b) => a.includes(`first`) ? -1 : 1)
  .sort((a, b) => +a.match(/\d+/) - +b.match(/\d+/));
document.querySelector(`pre`).textContent = 
  JSON.stringify(sorted, null, 2);
<pre></pre>
KooiInc
  • 119,216
  • 31
  • 141
  • 177