Reputation: 327
here is the array I want to sort:
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'},
];
Here is the code I use to run the natural sort.
console.log(documentData.sort((a,b)=>
a.title.toLowerCase().replace(/\>| |\-/g,'')
.localeCompare(
b.title.toLowerCase().replace(/\>| |\-/g,''),
undefined,{numeric:true, sensitivity:'base'})));
Here is the output I get
[ { 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' } ]
This is not the sorting I need. How can I sort an array of strings correctly if each string contains a date/time in addition to numerics and letters?
Upvotes: 2
Views: 154
Reputation: 386730
You could normalize date and time to ISO and sort by localeCompare
with options.
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; }
Upvotes: 1