swa49
swa49

Reputation: 17

Difference between sort compare function in Javascript

var arr = [undefined,null, NaN , Infinity];

sample.sort((a,b)=> a-b)

Answer :  [Infinity, NaN, null, undefined]

sample.sort((a,b)=> a>b ? 1 : -1)

Answer :  [null, NaN, Infinity, undefined]

Can anyone explain why there is a difference between the sort function?

Upvotes: 0

Views: 53

Answers (1)

Siva Kondapi Venkata
Siva Kondapi Venkata

Reputation: 11001

sort compare method does the following possible comparisons for both cases. This explains the discrepancy in output

enter image description here

const output = [];
[Infinity, NaN, null, undefined].forEach((a, i, arr) =>
  arr.forEach((b) => output.push({ 
    a, 
    b, 
    "a - b": a - b, 
    "a>b ? 1 : -1": (a>b ? 1 : -1) 
  }))
);

console.log(output)
console.table(output);

enter image description here

Upvotes: 1

Related Questions