how this java script works for sorting of numbers IN ASCENDING ORDER using sort() function.
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
08-09-2016 04:58 AM
<script>
var points = [40, 100, 1, 5, 25, 10];
document.getElementById("demo").innerHTML = points;
function myFunction() {
points.sort(function(a, b){return a - b});
document.getElementById("demo").innerHTML = points;
}
</script>
HOW THE SORT FUNCTION WORKS HERE?

- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
08-09-2016 05:01 AM
Hi Subrat,
This appears to be a simple ascending sort. From the looks of it, you got this from w3schools.
http://www.w3schools.com/js/tryit.asp?filename=tryjs_array_sort2
The sort() method can take an optional function to do the comparison of each element.
Is there a specific question you have about this?
By the way, you posted this to the Knowledge Management section of the community. This may have been better posted in the developer community. Something to consider for next time.
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
08-09-2016 05:05 AM
thanks chuck..

- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
08-09-2016 05:25 AM
Let me know if I have answered your question. If so, please mark my response as correct so that others with the same question in the future can find it quickly and that it gets removed from the Unanswered list.
If you are viewing this from the community inbox you will not see the correct answer button. If so, please review How to Mark Answers Correct From Inbox View.
Thank you

- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
08-09-2016 05:07 AM
Hello Subrat,
Array.sort is a function that can work with argument and without.
if you do points.sort(), it will sort the numbers by Unicode order.
But if you provide a sorting function with a function argument like
points.sort(function(a, b){return a - b});
then a function handles the values,
Please refer to possible best source for that:
Array.prototype.sort() - JavaScript | MDN
Regards,
Michal