我们有一个包含字符串和数字混合数据类型的数组,我们必须编写一个对数组进行排序的排序函数,以便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 ]