Reputation: 29
How does returning value1 - value2
end up in sorting, rather than returning the integral value that would be the result of mathematical substraction of the two?
var values = [ 213, 16, 2058, 54, 10];
values.sort(function(value1,value2){ return value1 - value2});
Upvotes: 0
Views: 1078
Reputation: 175007
The .sort()
method accepts a function that accepts two parameters (two elements), and returns a number to determine which element should come first. If the number is negative, value2
is bigger. If the number is positive, value1
is bigger. And if the number is equal to 0
, both elements are of the same size, and their order doesn't matter.
Therefore, returning value1 - value2
only works in this case because your elements are numbers. You'd have to employ some more sophisticated logic if they were something else.
Upvotes: 4
Reputation: 2249
Syntax: [1,2,3].sort(compareFunction)
, compareFunction
is called with two elements from the array at a time.
compareFunction(a, b)
returns a negative number, a
comes before b
.compareFunction(a, b)
returns 0
, they are equal and the two elements do not move.compareFunction(a, b)
returns a positive number, b
comes before a
.See more examples and detailed documentation at MDN:
Array.prototype.sort
: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort
Upvotes: 2
Reputation: 198436
value1 - value2
is not what's doing the sorting. sort
is. However, sort
takes a comparator parameter: a function that should return something negative if the first of the two arguments is smaller, 0
if they are equal, and something positive if the first of the two arguments is greater; and value1 - value2
does exactly that, for numeric elements.
Upvotes: 1