在 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
]

更新於: 14-10-2020

395 次瀏覽

開啟您的 職業生涯

完成課程獲得認證

開始
廣告