+ 3
What is sort() function in JavaScript? How does it work?
I recently searched in the internet about the sort() function in arrays of JavaScript but didn't understand much. Please provide a sample code and answer in reference to your code so that I understand better. Also provide the syntax. Thanks in advance.
5 Respostas
+ 1
@Aditya
The function that return a-b is a compare function of the sort function, to order the sort function set the sequence order.
Try to put the code
console.log("a="+a+" b="+b+" return:"+(a-b<0?"-":"+"))
inside the compare function, you can study how does the sort function works.
Basically the return of a-b will get a ascending order array result, whereas b-a will get a descending order array result.
+ 4
Example:
var num= [3,4,1,2];
num.sort();
result:
num [1, 2, 3, 4]
+ 3
Hopefully this sample can make you understand sort function better..
https://code.sololearn.com/W9ZDOjyA5Z77/?ref=app
+ 2
@Calvin why you have return a-b in your code? @Claudio Vidal After sorting can I get the array index as output instead of value?
+ 1
thanks I will try it