我正在尝试对具有可为空 bool 值和标题的对象数组进行排序。如果列表中的某个项目已设置为重要,则 "ReadUnderstood"
为 true
或 false
,如果不是,则为 空
。如果 "ReadUnderstood"
为 true
或 null
,但如果值为 false
,我希望列表按字母顺序排序>,我希望它位于列表顶部。
下面的代码最接近我想要的。这将按字母顺序返回列表,其中 "ReadUnderstood"
为 false
的项目位于列表顶部。但 "ReadUnderstood"
为 true
的项目最终会出现在列表的末尾,而不是按字母顺序排列。任何帮助将不胜感激。
items = [
{Title: 'A', ReadUnderstood: null},
{Title: 'C', ReadUnderstood: false},
{Title: 'E', ReadUnderstood: null},
{Title: 'B', ReadUnderstood: true},
{Title: 'D', ReadUnderstood: true},
{Title: 'F', ReadUnderstood: null},
]
items.sort((a, b) => {
return (b.ReadUnderstood != null && b.ReadUnderstood == false) - (a.ReadUnderstood != null && a.ReadUnderstood == false) || a.Title - b.Title;
})
Desired result:
items = [
{Title: 'C', ReadUnderstood: false},
{Title: 'A', ReadUnderstood: null},
{Title: 'B', ReadUnderstood: true},
{Title: 'D', ReadUnderstood: true},
{Title: 'E', ReadUnderstood: null},
{Title: 'F', ReadUnderstood: null},
]
最佳答案
你很接近。 compareFunction
应该返回一个数字,并根据它是正数、负数还是零,正在比较的两个项目 (a, b)
相对于彼此移动。减去 bool 值会返回一个数字。所以,第一个条件很好。对于字符串,您需要使用 localeCompare
按字母顺序对它们进行排序。
此外,您可以简化第一个条件。您不需要检查 null
并对 false
进行严格的相等检查。
items.sort((a, b) =>
(b.ReadUnderstood === false) - (a.ReadUnderstood === false)
|| a.Title.localeCompare(b.Title)
)
这是一个工作片段:
const items = [
{Title: 'A', ReadUnderstood: null},
{Title: 'C', ReadUnderstood: false},
{Title: 'E', ReadUnderstood: null},
{Title: 'B', ReadUnderstood: true},
{Title: 'D', ReadUnderstood: true},
{Title: 'F', ReadUnderstood: null},
]
items.sort((a, b) =>
(b.ReadUnderstood === false) - (a.ReadUnderstood === false)
|| a.Title.localeCompare(b.Title)
)
console.log(items)
关于JavaScript 按可为空的 bool 值对数组进行排序,然后按字符串排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57523665/