Are there JS gurus all around?
I needed to sort an array of files of the following format: `YYYY-MM?-DD?-N?` where month and day parts might be given as 1 or two digits, and N is the trailing number that might be omitted.
I came out with something so ugly that I was afraid to look at it.
.sort(
(a, b) => [a, b].map(
(e) => e.slice(2).split("-").map(
(i) => parseInt(i)
).reverse().reduce(
(a, b, idx) => a + b * 100 ** idx
)
).reduce((a, b) => a > b ? -1 : 1)
)
Please advice.
@mudasobwa чатжпт:
Yes, there are JavaScript gurus all around! Sorting an array of files with the given format can be done more efficiently and elegantly. Here's an alternative approach you can consider:
```javascript
const files = ["2021-05-05-2", "2020-12-01", "2022-01-15-1", "2019-10-10-4"];
files.sort((a, b) => {
const [aDate, aNum] = a.split('-');
const [bDate, bNum] = b.split('-');
const [aYear, aMonth, aDay] = aDate.split('-').map(Number);
const [bYear, bMonth, bDay] = bDate.split('-').map(Number);
const aNumber = Number(aNum || 0);
const bNumber = Number(bNum || 0);
return (
new Date(aYear, aMonth - 1, aDay) - new Date(bYear, bMonth - 1, bDay) ||
aNumber - bNumber
);
});
console.log(files);
```
This code breaks down the filenames into their respective parts (year, month, day, number), converts them to numbers, and then uses the `Array.prototype.sort()` method to sort the files first by date and then by the number.
@mudasobwa чатжпт:
Yes, there are JavaScript gurus all around! Sorting an array of files with the given format can be done more efficiently and elegantly. Here's an alternative approach you can consider:
```javascript
const files = ["2021-05-05-2", "2020-12-01", "2022-01-15-1", "2019-10-10-4"];
files.sort((a, b) => {
const [aDate, aNum] = a.split('-');
const [bDate, bNum] = b.split('-');