Gan
Gan

Reputation: 164

Sorting method why difference return

Why when sorting we do something like this?

employees.sort(function(a, b){
 return a.age-b.age
}

Why it is enough to return the difference between 2 values?

Upvotes: 0

Views: 40

Answers (1)

MistyK
MistyK

Reputation: 6232

If function returns positive value it means that a object is bigger. If function returns 0 it means that a is equal to b. If function return negative value it means that b is bigger.

It's enough to compare all elements in collection, the only information it needs, it's how compare any two elements.

Upvotes: 2

Related Questions