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

129
Views
Sorting Array Elements with .sort()

I'd like to understand intrinsically, how does array.sort() method works? Like, under the hood, what happens? Is this a kind of data structure that works really fast? Is there a for.each hidden somewhere in the code because I can't figure out what happens with a and b

let numbers = [ 0, 1, 10, 2, 20, 3, 30 ];
numbers.sort((a,b) =>{
    if(a > b) return 1;
    if(a < b) return -1;
    return 0;
});

console.log(numbers);

Plus, how can the above code become this:

let numbers = [ 0, 1, 10, 2, 20, 3, 30 ];
numbers.sort((a, b) => a - b);
console.log(numbers);

#EDIT1 Ok, I got that if the result of a-b is negative a get first position, otherwise are swapped, if they are equal they stay in position. My question is: does Javascript engine sort every time till there is no more swapping?

Let's pretend I have  arr = [1,20,10,5,2] 
1st round: a=1 b=20 result  [1,20,10,5,2]
2nd round: a=10 b=20 result [1,10,20,5,2]
3rd round: a=20 b=5 result  [1,10,5,20,2]
end of this cycle becomes   [1,10,5,2,20] 

Array is not fully sorted. Does it start all over again? Where and how does the engine know that the sorting has finished?

about 4 years ago · Juan Pablo Isaza
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!