Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

103
Views
Deterministic string compare in JS/TS?

I am looking for a deterministic way of sorting a list of strings.

Sorting a string of course often leads to the suggestion to use String.localeCompare. But the order must be deterministic, unrelated to the computer where it is running on.

The hardcore solution I came up with is hashing each string and compare these instead with a locale option en. Is there an easier solution?

The strings can be English, German, Chinese, Japanese, ...

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

Oddly, what fits your requirements is...the default sort:

theStrings.sort();

That sorts according to the UTF-16 code units in the strings, which doesn't vary by computer/locale/whatever. It treats the strings as (effectively) a series of 16-bit numbers (Unicode code units, to be precise).

From the specification:

If comparefn is not undefined, it should be a function that accepts two arguments x and y and returns a negative Number if x < y, a positive Number if x > y, or a zero otherwise.

And the < and > operators are defined by the abstract IsLessThan operation in the specification, which compares by the code units in the string.

about 4 years ago · Juan Pablo Isaza Report

0

Two solutions:

  • use a specific locale, not the current one like localeCompare. JS supports this through the Intl.Collator:

    arr.sort(new Intl.Collator('en').compare)
    

    Choose whatever language you need.

  • use the standard lexicographic comparison that the builtin </> operators for strings supply:

    arr.sort((a, b) => +(a>b)||-(b>a))
    arr.sort()
    
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!