在 Javascript 中使用 sort() 將 NaN 推到陣列末尾
我們有一個包含字串和數字混合資料型別的陣列,我們必須編寫一個排序函式,使陣列排序,以便 NaN 值始終位於底部。
該陣列應包含前面的所有有效數字,後跟字串文字,後跟 NaN。
程式碼如下 -
const arr = [344, 'gfd', NaN, '', 15, 'f',176, NaN, 736, NaN, 872, 859,
'string', 13, 'new', NaN, 75];
const sorter = (a, b) => {
if(a !== a){
return 1;
}else if(b !== b){
return -1;
}
return typeof a === 'number' ? -1 : 1;
};
arr.sort(sorter);
console.log(arr);輸出
在控制檯中的輸出 -
[ 75, 13, 859, 872, 736, 176, 15, 344, 'gfd', '', 'f', 'string', 'new', NaN, NaN, NaN, NaN ]
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP