I have a filelist object that contains over 1000 image files. I want the object to be sorted by file name, which is alphanumeric. In other words, I want to do a natural sort. The file names are like this:
d_1_ct.png
d_2_ct.png
d_3_ct.png
d_4_ct.png
Turning the filelist object into an array by doing [].slice.call(filelist_object)
or Array.from(filelist_object)
and then calling sort()
results in alphabetical sort only. How can I make the filelist object naturally sorted on file name?
I am okay with turning it into an array, as long as I'm able to display the image files using URL.createObjectURL()
on the array elements.
Natural-sorting alphanumeric strings is not what I'm looking for, though the names of my files in the filelist object are alphanumeric strings. The filelist object contains the following properties:
0: File
lastModified: 1493435514308
lastModifiedDate: Sat Apr 29 2017 08:41:54 GMT+0530 (India Standard Time)
name: "d_1_ct.png"
size: 5307
type: "image/png"
webkitRelativePath: "img/d_1_ct.png"
__proto__:File
I want to sort on either name
or webkitRelativePath
, while retaining all the properties of the filelist object, as I am using the index numbers of the object to display the images.
There's now a much easier way using localeCompare
: http://fuzzytolerance.info/blog/2019/07/19/The-better-way-to-do-natural-sort-in-JavaScript/
const items = ['3rd', 'Apple', '24th', '99 in the shade', 'Dec', '10000', '101', '$1.23']
items.sort((a, b) => a.localeCompare(b, navigator.languages[0] || navigator.language, {numeric: true, ignorePunctuation: true}))
console.log(items)
// [ "$1.23", "3rd", "24th", "99 in the shade", "101", "10000", "Apple", "Dec" ]
Additionally, you can speed this up by declaring the collator object beforehand.