DEV Community

ADEKOLA Abdwahab
ADEKOLA Abdwahab

Posted on

How To Sort Array of Strings

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 }])
Enter fullscreen mode Exit fullscreen mode

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);
Enter fullscreen mode Exit fullscreen mode

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.

repl sorted the array of strings

😲

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 -

sorting array of strings with guarantee

Have you encountered a similar issue before? Or an inconsistency on REPL?

I would love to hear from you.

Top comments (0)