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

98
Views
Behind the scenes of Javascript sort comparison
const arr = [3, 89, 1, 120, 23];
console.log(arr.sort((a, b) => a - b));

The code above sorts the array. However, how does sort know that a = current index and that b = next index??? We never specify to sort what they are and to what they're equal to.

And after that, how does .sort figure out that the returned value from that anonymous arrow function means that the value need to be moved? Example: [1, 2]

sort((a, b) => a - b))
sort((1, 2) => 1 - 2))
sort((1, 2) => -1))
sort(-1));

See? How does .sort know what to do with -1?

I've been Googling and YouTubing for the past 2 hours and can't find the answer... :(

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

0

However, how does sort know that a = current index and that b = next index?

No, a is current value, b is next value.
The sort function you see is not just run once, it runs again and again, depending on which length your array has.
In your case, in the first run, a equals 3 and b equals 89. And the second run, a equals 3, b equals 1.

The sort function is work for an array of strings, so if you need to sort an array of strings, just use array.sort()
Compare function is required when you need to sort a numeric array.
If not, it gets the wrong result: "25" is bigger than "100", because "2" is bigger than "1".

Compare function just return three kinds of number:

  1. Negative number (-1,-2,...): it means a less than b
  2. Zero (0): it means a equals b
  3. Positive number (1,2,3..): it means a greater than b

So, you can more clearly return inside the Compare function like this:

if(a === b)
    return 0;
if(a < b)
    return -1;
return 1;

But, simpler, you can a using a trick, you just need to return a-b to determine whether a is greater than b or not.

See more: JavaScript Sorting Arrays

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!