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: http://www.codewars.com/kata/572df796914b5ba27c000c90) :
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?
The sort() method sorts the elements of an array in place and returns the reference to the same array, now sorted. The default sort order is ascending, built upon converting the elements into strings, then comparing their sequences of UTF-16 code units values.
return 1 in the main function means that the program does not execute successfully and there is some error. return 0 means that the user-defined function is returning false. return 1 means that the user-defined function is returning true.
-1 means the first goes before the second, 1 means it goes after, and 0 means they're equivalent. The sort function uses the comparisons in the function you pass it to sort the function.
The sort() sorts the elements of an array. The sort() overwrites the original array. The sort() sorts the elements as strings in alphabetical and ascending order.
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
(a
will be ranked beforeb
)If
functionComparison(a, b)
returns 0
, we leavea
andb
unchanged 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 sortb
with 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With