【发布时间】:2021-09-09 10:00:02
【问题描述】:
我正在尝试通过两个条件对数组进行重新排序。确保 Pos 10 出现在单个数字之后,并且遵循特定的顺序。
我尝试优先考虑包含first 的字符串,但如果我想按字母数字顺序排序,它会将 A 重置为顶部。我怎样才能选择预期的结果?
const arr = [
'Pos 10 second',
'Pos 10 A third',
'Pos 10 first',
'Pos 1 second',
'Pos 1 A third',
'Pos 1 first',
'Pos 2 second',
'Pos 2 A third',
'Pos 2 first',
]
const res = arr.sort((a, b) => {
if (a.includes('first')) {
return -1
} else {
return 1
}
}).sort((a, b) => a.localeCompare(b, 'en', { numeric: true}))
console.log(res)
/* Expected output
[
'Pos 1 first',
'Pos 1 second',
'Pos 1 A third',
'Pos 2 first',
'Pos 2 second',
'Pos 2 A third',
'Pos 10 first',
'Pos 10 second',
'Pos 10 A third'
] */
【问题讨论】:
-
您需要保留单词的优先级列表并给它们一个数字并在您的排序算法中使用它
-
@HDM91 我知道,但是按条件排序和按本地比较排序,你能重现预期结果吗?
-
如何在第一排序中移动区域设置比较?
标签: javascript arrays sorting