can anyone explain me this code | Sololearn: Learn to code for FREE!

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);

12/8/2020 4:39:42 AM

Priyal Vyas

2 Answers

New Answer

+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

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.