I am studying Javascript and currently learning the .sort() function for arrays. I understood that it can take either no argument or one between a-b and b-a.
What I don't understand however is the use of return 0, return -1 and return 1. Here is an example (source: ) :
var arr=[1,2,3,4,5,6,100,999] arr.sort((a,b)=>{ if (a%2==b%2) return a-b; if (a%2>b%2) return -1; return 1; }) console.log(arr) //output: [ 1, 3, 5, 999, 2, 4, 6, 100 ] I understand what it's supposed to do, i.e. separate odd and even numbers and sort them in ascending order. But what is the meaning of return -1 and return 1? Can someone walk me through this function step by step?
I tried to play with the code and change some values, for example change return -1 to return 0, to try to understand how it could work, but I still don't get it.
Where can I find resources with details about that return element?
2 Answers
According to the sort docs:
If the parameter functionComparison is supplied, the elements of the array are sorted according to the return value of the comparison function. If a and bare two elements to compare, then:
If
functionComparison(a, b)is less than0, we sort a with an index less thanb(awill be ranked beforeb)If
functionComparison(a, b)returns 0, we leaveaandbunchanged relative to each other, but sorted with respect to all the other elements. Note: The ECMAScript standard does not guarantee this behavior, so all browsers (eg Mozilla versions prior to 2003) do not respect this. IffunctionComparison(a, b)is greater than0, we sortbwith an index less thana.
functionComparison(a, b)must always return the same result from the same pair of arguments. If the function returns inconsistent results, then the order in which the items are sorted is not defined.
Now if a > b, returning 1 or a positive value is one and the same thing, similarly, if a < b then returning -1 or the difference is the same. If both are equal the difference is 0 and hence return 0
Where can I find resources with details about that return element?
return value is for the comparator function. As per spec
If
comparefnis notundefined, it should be a function that accepts two arguments x and y and returns a negative value if x < y, zero if x = y, or a positive value if x > y.