这是我要排序的数组:
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' } ]
这不是我需要的排序。如果每个字符串除数字和字母外还包含日期/时间,如何正确地对字符串数组进行排序?
答案 0 :(得分:1)
您可以将日期和时间标准化为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; }