## DEV Community is a community of 753,038 amazing developers

We're a place where coders share, stay up-to-date and grow their careers.

# Discussion on: I failed an interview because of an algorithm

## Replies for: As a self-taught web developer going on 25 years now I am sympathetic and if it helps you out at all I would have failed that question coming at it... Wow, brilliant 1-liner solution! I didn't know anything about `Intl.Collator`. I investigated a little bit more about it. This also works:

``````const sortVersions = (unsortedVersions) => {
return unsortedVersions.sort((a, b) => b.localeCompare(a, 'en', {numeric: true}));
}
``````

This is the original solution I came up with in 17 min. (I timed myself to make sure I don't go over 30 min)

``````const sortVersions = (unsortedVersions) => {
const vers = unsortedVersions.map((ver) =>
ver.split(".").map((v) => Number(v))
);
vers.sort((a, b) => {
for (let i = 0; i < Math.min(a.length, b.length); i++) {
if (a[i] !== b[i]) return b[i] - a[i];
}
return a.length > b.length ? -1 : 1;
});
return vers.map((v) => v.join("."));
};
`````` Danny Engelman • Edited on

You are all still thinking in Numbers. (including those who interview)
The localCompare won't sort "2.1.0a" properly

Key is to convert Numbers to Letters, so 2.1.0a becomes cbaa and then sort

explanation:
stackoverflow.com/questions/683259...

Or in one line

``````const sortVersions = (x, v = (s) => s.match(/(\d+)|[a-z]/g).map(c => c == ~~c ? String.fromCharCode(97 + c) : c)) => x.sort((a, b) =>v(b) < v(a) ? 1 : -1)
``````

` Or just do something like "2.1.0a" becomes " 2 1 0 a", then it will sort correctly.

``````

const sortVersions = (unsortedVersions) => {
const format = (n) => n.split(/[.a-z]/g).map(c => c.padStart(5)).join("");
return unsortedVersions.sort((x, y) => {
return format(x) >= format(y) ? 1 : -1;
});
};

sortVersions(['2.5.10.4159', '1.0.0', '0.5', '0.4.1', '1', '1.1', '1.1a', '2.5.0', '2a', '1.1a-final', '2.5.10', '10.5', '1.25.4', '1.2.15'])
//["0.4.1","0.5","1","1.0.0","1.1","1.1a","1.1a-final","1.2.15","1.25.4","2a","2.5.0","2.5.10","2.5.10.4159","10.5"]

`````` 