English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
There are two methods for array sorting in JavaScript: reverse() and sort().
The reverse() method will reverse the order of the array items:
var arr = [1,2,3,4,5]); arr.reverse(); alert(arr); //5,4,3,2,1
The sort() method will sort the array items in ascending order, the sort() method will call the tostring() method of each array item, even if each item in the array is a number, the sort() method compares strings:
var arr = [1,2,11,15,5]); arr.sort(); alert(arr); // 1,11,15,2,5
This method is not the best solution in many cases, therefore the sort() method can accept a comparison function as a parameter. The comparison function needs two parameters, if the first parameter should be before the second parameter, it should return a negative number, if the two parameters are equal, it should return 0, and if the first parameter should be after the second parameter, it should return a positive number:
var arr = [1,2,11,15,5]); arr.sort(function(val1,val2{ return val1-val2; }); alert(arr); // 1,2,5,11,15
Since the comparison function affects the sorting result by returning a value less than zero, equal to zero, or greater than zero, the subtraction operation can handle these situations very well.
Summary
The above is the detailed explanation of the JavaScript array sorting methods reverse() and sort() introduced by the editor for everyone, hoping it will be helpful to everyone. If you have any questions, please leave a message, and the editor will reply to everyone in time!
Statement: The content of this article is from the Internet, the copyright belongs to the original author. The content is contributed and uploaded by Internet users spontaneously. This website does not own the copyright, does not edit the content manually, and does not assume any relevant legal liability. If you find any content suspected of copyright infringement, please send an email to notice#w3Please send an email to codebox.com (replace # with @ when sending an email) to report any violations, and provide relevant evidence. Once verified, this site will immediately delete the infringing content.