0

can anyone explain me this code

var a = ['c', 'a', 'd', 'b', 'aa']; var b = [9, 2, 13, 7, 1, 12, 123]; // Sort in descending lexicographical order using a compare function a.sort(function(x, y) { return x < y; } ); b.sort(function(x, y) { return x < y; } ); output:- a: [ 'd', 'c', 'b', 'aa', 'a' ] b: [ 123, 13, 12, 9, 7, 2, 1 ] console.log('a:', a); console.log('b:', b);

8th Dec 2020, 4:39 AM
Priyal Vyas
Priyal Vyas - avatar
2 ответов
+ 2
Hello, By default, the sort() function sorts values as strings. This works well for strings ("a" comes before "b"). However, if numbers are sorted as strings, "25" is bigger than "100", because "2" is bigger than "1". the purpose of the compare function is to define an alternative sort order. The compare function should return a negative, zero, or positive value, depending on the arguments: function(x, y) { return x < y; } When the sort() function compares two values, it sends the values to the compare function, and sorts the values according to the returned (negative, zero, positive) value. If the result is negative a is sorted before b. If the result is positive b is sorted before a. If the result is 0 no changes are done with the sort order of the two values. For more info refer this: https://stackoverflow.com/a/39361888/11269963
8th Dec 2020, 5:25 AM
AjayGohil
0
thank u so much !! I understood how it works. The compare function will compare each of the elements if a is less than b , a is sorted first.
8th Dec 2020, 4:42 PM
Priyal Vyas
Priyal Vyas - avatar