如何解决排序可能包含JavaScript中未定义的数组
我有一个要排序的字符串数组。该数组可能包含一些未定义的值。在这种情况下,对于升序,值应该放在最后,而对于降序,值应该放在开头。
我尝试过
var content = ["Anuja",undefined,"Ranbir","undefined"];
content.sort(function(a,b) {
if (a == undefined) {
a = ""
}
if (b == undefined) {
b = ""
}
return a.localeCompare(b);
});
console.log(content)
使用此代码,我得到[“”,“”,“ Anuja”,“ Ranbir”],但我的要求是[“ Anuja”,“ Ranbir”,“”,“”]。
解决方法
这不是小事,但我找到了办法
let content = ["Anuja",null,"Ranbir",null]; // note the undefined entry at index 3
// one of the few ways to detect undefined entries
// .map IGNORES undefined entries
for (let i=0;i<content.length;i++) {
content[i] = content[i] || ""; // you may want to test for 0 here
}
const asc = (a,b) => {
if (a === "") return 1; // can be DRY'd using *dir where dir is -1 or 1
if (b === "") return -1;
return a.localeCompare(b);
};
const dsc = (a,b) => {
if (a === "") return -1;
if (b === "") return 1;
return b.localeCompare(a);
}
content.sort(asc);
console.log(content)
content.sort(dsc);
console.log(content)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。