How To Sort Array of Strings
ADEKOLA Abdwahab
Posted on July 5, 2024
I was building a pdf merger that takes two pdf files, merge them, then return a single file - result of the merging.
There is a requirement that the files must be in order, i.e. a particular file has to be at the top.
Since I exposed this via an endpoint, and I am using multer to manage file uploads as shown below
upload.fields([{ name: 'pdf1', maxCount: 1 }, { name: 'pdf2', maxCount: 1 }])
Multer would not order the files, and there is no guarantee on how what I would get from Multer I had to resort to sorting the array of 'processed files' from multer. I sorted by 'filename.'
files.sort((a, b) => a.filename - b.filename);
To my greatest shock, the array was not sorted.
I hurriedly went to my terminal. launched REPL and tried it, then it got sorted on REPL.
😲
How? Why?
Then I went back to the basics of sorting, comparing, and returning -1, 0, or 1 if the first argument is lesser, equal, or greater than the second argument, respectively.
Like this -
Have you encountered a similar issue before? Or an inconsistency on REPL?
I would love to hear from you.
Posted on July 5, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
November 28, 2024