2019年2月16日 星期六

[ JS 常見問題 ] How to sort an array of integers correctly

Source From Here 
Question 
Trying to get the highest and lowest value from an array that I know will contain only integers seems to be harder than I thought: 
  1. var numArray = [140000, 104, 99];  
  2. numArray = numArray.sort();  
  3. alert(numArray)  
I'd expect this to show 99, 104, 140000. Instead it shows 104, 140000, 99. So it seems the sort is handling the values as strings. Is there a way to get the sort function to actually sort on integer value? 

How-To 
By default, the sort method sorts elements alphabetically. To sort numerically just add a new method which handles numeric sorts (sortNumber, shown below): 
  1. function sortNumber(a,b) {  
  2.     return a - b;  
  3. }  
  4.       
  5. var numArray = [140000, 104, 99];  
  6. numArray.sort(sortNumber);  
  7. alert(numArray.join(","));  
You can use ES6 arrow functions: 
  1. numArray.sort((a, b) => a - b); // For ascending sort  
  2. numArray.sort((a, b) => b - a); // For descending sort  


沒有留言:

張貼留言

[Git 常見問題] error: The following untracked working tree files would be overwritten by merge

  Source From  Here 方案1: // x -----删除忽略文件已经对 git 来说不识别的文件 // d -----删除未被添加到 git 的路径中的文件 // f -----强制运行 #   git clean -d -fx 方案2: 今天在服务器上  gi...