Email or username:

Password:

Forgot your password?
Aleksei � Matiushkin

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.

11 comments
Nanao Ei

@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('-');

Aleksei � Matiushkin

@exo дайте угадаю: вы никогда в глаза не видели джаваскрипт, но думаете, что чатжпт может написать рабочий код, да?

Я бы постеснялся.

Nanao Ei

@mudasobwa а чего стесняться?! Есть вопрос, загрузил в жпт, получил какой-то ответ. Но если твой блог не место для дискуссий, то ок

Aleksei � Matiushkin

@exo хуета выше не работает в принципе, там ошибка на ошибке, и оно буквально ни-ху-я не сортирует.

Чатжпт — поделие для дебилов, нужно вообще мозгов не иметь, чтобы просить его написать (или тем паче отрихтовать) код.

Причем тут вообще дискуссия?

Rustem Zakiev 🔥

@mudasobwa looks like this sorter is going to provide other than intended result - if you have that trailing N in any of the names, that name goes above those without one.
Is having filenames with proper leading zeroes in MM and DD not an option?

Aleksei � Matiushkin

@willpraxis the issue with trailing N is arguably intended, and might be easily fixed in my code, if needed.

No, I am to allow omitting leading zeroes before numbers, as we, human beings, usually do (unlike ISO 8861 automats.)

Rustem Zakiev 🔥

@mudasobwa
off topic: when writing a date in yyyy-mm-dd format, I prefer having leading zeroes, it looks more aesthetic to me.

I am a human, I pass the captcha almost every time. )

Aleksei � Matiushkin

@willpraxis nah, me too, but there are psychos in the wild who hate zeros and save keystrokes

Rustem Zakiev 🔥

@mudasobwa my ugly shot:
.sort(
(a,b) => [a, b].map(
(e) => e.slice(2).split("-").map(
(i) => i.length < 2 ? "0" + i : i
).join("-")
).reduce((a, b) => a > b ? -1 : 1)
)

Aleksei � Matiushkin

@willpraxis yeah, I thought about it, but I was unsure how JS wouls sort strings :)

Aleksei � Matiushkin

@willpraxis I get accustomed to that everything in Elixir is sortable in the expected way, including but not limited to arrays (lists) of four elements

Go Up