简体   繁体   中英

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
    })

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM