javascript - 对可能包含 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)
推荐阅读
- python - 将 CSV 循环到 URL
- php - Class Organisation of Api Wrappers
- python - 不执行无故不执行的 True if 语句
- c# - 从表单中检索多行/记录
- raku - 如何将数组插入到数组数组中?
- spring - Spring Webflow - 转换器类型的问题
- postgresql - 如何在 Express.js 中实现 postgraphile
- r - 从导入的文本文件中为单词着色,并保存为格式化的 Word 文档
- python - 如何使用 pyaudio 处理上一个、即时和下一个缓冲区以进行重叠?
- syntax - 如何在不破坏代码的情况下在 Python shell 中使用不同的缩进获取换行符