+ 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.

30th Apr 2017, 3:35 PM
Aditya Kshitiz
Aditya Kshitiz - avatar
5 Respuestas
+ 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.
1st May 2017, 1:10 AM
Calviղ
Calviղ - avatar
+ 4
Example: var num= [3,4,1,2]; num.sort(); result: num [1, 2, 3, 4]
30th Apr 2017, 3:41 PM
⏩▶Clau◀⏪
⏩▶Clau◀⏪ - avatar
+ 3
Hopefully this sample can make you understand sort function better.. https://code.sololearn.com/W9ZDOjyA5Z77/?ref=app
30th Apr 2017, 4:23 PM
Calviղ
Calviղ - avatar
+ 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?
30th Apr 2017, 5:09 PM
Aditya Kshitiz
Aditya Kshitiz - avatar
+ 1
thanks I will try it
1st May 2017, 12:45 PM
Aditya Kshitiz
Aditya Kshitiz - avatar