Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

localeCompare for Natural Sort?

I'm developing a comic book reader and I have a few files (images) that the user uploads (File objects) and I'm using their filenames in order to sort them in the correct order.

I tried using localeCompare to perform a natural sort on them, but no luck...

The pages should be sorted in this manner:

page1
page2
page3
etc.

However, with my current code they are sorted like this:

page1  <------
page10
page11
page12
page13
page14
page15
page16
page17
page18
page19
page2  <------
page20
etc.

Here is the code I'm using in order to sort correctly:

(split() function is used to get image file name)

comicImages.sort((a, b) => {
        let aSplit = a.webkitRelativePath.split('/')
        let bSplit = b.webkitRelativePath.split('/')
        let compareResult = aSplit[2].localeCompare(bSplit[2], {numeric: true, sensitivity: 'base'})

        return compareResult
    })
like image 483
skubri Avatar asked Oct 24 '25 03:10

skubri


1 Answers

localeCompare takes 3 arguments. The options object ({numeric: true, sensitivity: 'base'}) should be the third argument not the second.

//----------------------------------------v
input.sort((a,b) => a.localeCompare(b, undefined, {numeric: true, sensitivity: 'base'}))

Live Example:

const input = [    "page1",
    "page10",
    "page11",
    "page12",
    "page13",
    "page14",
    "other1",
    "other10",
    "other11",
    "other12",
    "other13",
    "other14",
    "other15",
    "other16",
    "other17",
    "other18",
    "other19",
    "other2",
    "other20",
    "page15",
    "page16",
    "page17",
    "page18",
    "page19",
    "page2",
    "page20",
];

//----------------------------------------v
input.sort((a,b) => a.localeCompare(b, undefined, {numeric: true, sensitivity: 'base'}))

console.log(...input)
like image 136
adiga Avatar answered Oct 25 '25 16:10

adiga



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!