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.

SurveyJS custom survey software

JavaScript UI Libraries for Surveys and Forms

SurveyJS lets you build a JSON-based form management system that integrates with any backend, giving you full control over your data and no user limits. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more.

Learn more

Top comments (0)

nextjs tutorial video

Youtube Tutorial Series πŸ“Ί

So you built a Next.js app, but you need a clear view of the entire operation flow to be able to identify performance bottlenecks before you launch. But how do you get started? Get the essentials on tracing for Next.js from @nikolovlazar in this video series πŸ‘€

Watch the Youtube series