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

88
Views
Why does javascript sort on arrays make different amounts of comparisons?
var arr=[..."12345678"]
var res=[];
var cnt=0;
function comparefn(a,b,c){
  var rnd1;
  console.log(`a=${a} , b=${b} , arr=${arr}`)
rnd1=Math.random() - 0.5;
  res.push(`${++cnt}) (${rnd1}) ${a},${b}` )
  
  
  return rnd1;
}

console.log(arr.sort(comparefn));

console.log(res.join(", "))

If I change the return value on the compare function (comparefn) then if it was a return of 1 then it would compare 28 times. If the return value of the compare function (comparefn) is 0 (zero) then is only compares it 7 times. Now, if the return value is Math.random() - 0.5 then it compare a variable number of times, from about 7 to 28 (which I suppose is the maximum number of 2 item permutations)? Some strange bits - on MDN is says 'Note: compareFunction(a, b) must always return the same value when given a specific pair of elements a and b as its two arguments. ' I am not sure why it says that, because this function returns a random number (-1 to plus 1 approx) for ANY 2 items. As you may know this is the algo for the quick shuffle on an array (Math.random() - 0.5). I have found though, with 8 items that 0.3 gives a more natural order of items, that is to say that 0.5 used to favour the low numbers being in the start of the array but with 0.3 the array used to start with more different numbers - of course this is just by my eye (it could just be with eight items).

Ref: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort

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!