【问题标题】:Order array alphanumercially and with a condition按字母数字顺序排列数组并带有条件
【发布时间】: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


【解决方案1】:

对于第二次排序,在字符串值中的数字上使用match,转换为Number

const sorted = [
    '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',
  ]
  .sort((a, b) => a.includes(`first`) ? -1 : 1)
  .sort((a, b) => +a.match(/\d+/) - +b.match(/\d+/));
document.querySelector(`pre`).textContent = 
  JSON.stringify(sorted, null, 2);
<pre></pre>

【讨论】:

  • @Kooilnc 谢谢,但预期的结果应该是A third 低于second
  • 实际上我只运行了这两种方法并且效果很好
  • 是的,只是当您在 stackoverflow 上运行它时,出于某种原因它首先出现,非常感谢!
猜你喜欢
  • 2021-06-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-02-28
  • 1970-01-01
相关资源
最近更新 更多