2

I have files named as follows:

X-1.pdf
X-2.pdf
X-3.pdf
.
.
.
X-15.pdf

When ordered based on string value, the sequence is as follows:

X-1.pdf
X-10.pdf
X-11.pdf
.
.
.

Assuming these files are stored in a string array, how would I order the array so that the files appear in the 'expected' manner ie

X-1.pdf
X-2.pdf
.
.
.
Hoa
  • 19,858
  • 28
  • 78
  • 107

2 Answers2

3

You can use localeCompare with the numeric option set to true:

console.log(
  ['X-11.pdf',
    'X-1.pdf',
    'X-9.pdf',
    'X-10.pdf',
    'X-2.pdf',
  ].sort((a, b) => a.localeCompare(b, 'en', {numeric: true }))
)
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
-1

I think the best way would be to remove the alpha characters, and sort that way.

const files = ['X-1.pdf', 'X-10.pdf', 'X-2.pdf', 'X-3.pdf', 'X-4.pdf', 'X-11.pdf', 'X-5.pdf', 'X-6.pdf', 'X-8.pdf', 'X-9.pdf', 'X-12.pdf', 'X-13.pdf', 'X-14.pdf', 'X-15.pdf', 'X-7.pdf']

files.sort((a, b) => parseInt(b.replace(/[^0-9]/, '')) - parseInt(a.replace(/[^0-9]/, '')))

console.log(files)
Get Off My Lawn
  • 34,175
  • 38
  • 176
  • 338