DEV Community

ADEKOLA Abdwahab
ADEKOLA Abdwahab

Posted on

1 1

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.

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

Top comments (0)

AWS Security LIVE!

Tune in for AWS Security LIVE!

Join AWS Security LIVE! for expert insights and actionable tips to protect your organization and keep security teams prepared.

Learn More

👋 Kindness is contagious

Explore a sea of insights with this enlightening post, highly esteemed within the nurturing DEV Community. Coders of all stripes are invited to participate and contribute to our shared knowledge.

Expressing gratitude with a simple "thank you" can make a big impact. Leave your thanks in the comments!

On DEV, exchanging ideas smooths our way and strengthens our community bonds. Found this useful? A quick note of thanks to the author can mean a lot.

Okay