自然排序字符串,其中包含数字、字母以及javascript中的日期和时间的问题

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (1)
  • 关注 (0)
  • 查看 (200)

这是我要排序的数组:

let documentData=[
{'title':'01 Documents >File0010-Donia5,06/14/2018,1.14.03 PM.pdf'},
{'title':'01 Documents >File0010-Donia5,06/14/2018,5.14.03 AM.pdf'},
{'title':'04 Images > Image0010-image59323.jpg'},
{'title':'04 Images > Image0010-image44005.jpg'},
{'title':'01 Documents >File0010-Donia5,08/04/2018,5.14.03 PM.pdf'},
{'title':'01 Documents >File0010-Donia5,12/14/2018,10.14.03 AM.pdf'},
    ];

这是我用来运行自然排序的代码。

console.log(documentData.sort((a,b)=>
      a.title.toLowerCase().replace(/\>| |\-/g,'')
        .localeCompare(
            b.title.toLowerCase().replace(/\>| |\-/g,''),
            undefined,{numeric:true, sensitivity:'base'})));

这是我得到的输出

[ { title: '01 Documents >File0010-Donia5,06/14/2018,1.14.03 PM.pdf' },
  { title: '01 Documents >File0010-Donia5,06/14/2018,5.14.03 AM.pdf' },
  { title: '01 Documents >File0010-Donia5,08/04/2018,5.14.03 PM.pdf' },
  { title: '01 Documents >File0010-Donia5,12/14/2018,10.14.03 AM.pdf' },
  { title: '04 Images > Image0010-image44005.jpg' },
  { title: '04 Images > Image0010-image59323.jpg' } ]

这不是我需要的排序。如果每个字符串除了数字和字母之外还包含日期/时间,我如何才能正确排序字符串数组?

提问于
用户回答回答于

你可以将日期和时间标准化为ISO并localeCompare使用选项排序。

function normalize(s) {
    return s
        .replace(/(\d\d)(\/)(\d\d)(\/)(\d\d\d\d)/g, '$5-$3-$1')
        .replace(/(\d{1,2}\.\d\d\.\d\d)\s([AP]M)/g, (_, t, m) => {
            var p = t.split('.').map(Number);
            if (p[0] === 12) {
                p[0] = 0;
            }
            if (m === 'PM') {
                p[0] += 12;
            }
            return p.map(v => v.toString().padStart(2 , '0')).join(':');
        });
}

let documentData = [{ title:'01 Documents >File0010-Donia5,06/14/2018,1.14.03 PM.pdf' }, { title:'01 Documents >File0010-Donia5,06/14/2018,5.14.03 AM.pdf' }, { title:'04 Images > Image0010-image59323.jpg' }, { title:'04 Images > Image0010-image44005.jpg' }, { title:'01 Documents >File0010-Donia5,08/04/2018,5.14.03 PM.pdf' }, { title:'01 Documents >File0010-Donia5,12/14/2018,10.14.03 AM.pdf' }];
    
documentData.sort((a, b) => normalize(a.title).localeCompare(normalize(b.title), undefined, { numeric: true, sensitivity: 'base' }));

console.log(documentData);

.as-console-wrapper { max-height: 100% !important; top: 0; }

扫码关注云+社区

领取腾讯云代金券