loading words...

Apr 18, 2019 23:12:57

natsort

by @swizecteller | 201 words | ๐Ÿฃ | 116๐Ÿ’Œ

Swizec Teller

Current day streak: 0๐Ÿฃ
Total posts: 116๐Ÿ’Œ
Total words: 32303 (129 pages ๐Ÿ“„)

PSA: Always use natsort in UI.

We had a hairy bug, undiscovered for 2 months, because alphabetically sorted UI in an internal tool caused me to use the wrong "latest" version of a config and the config I created off of it was way wrong.

---

Here's why natsort is important y'all.

Natsort is short for natural sort. ie ๐Ÿ‘‰ how you and I think about sorting versus how computers think about sorting.

You may not have thought about this before ...

---

Take a series of numbers: 1, 45, 41, 2, 52, 19

Sorted like this, right? 1, 2, 19, 41, 45, 52

What does a computer think?

[1, 45, 41, 2, 52, 19].sort()

> [1, 19, 2, 41, 45, 52]

---

Ok sorting works with numbers, now check this out.

How would you sort "1", "45", "41", "2", "52", "19"?

---

Here's how a computer sorts those numbers as strings

๐Ÿคจ

That's wrong isn't it?

---

It FEELS wrong to a human, but it's correct. Those numbers are alphabetically sorted.

Alphabet sort compares strings character-by-character. It only checks the next character as a tie-breaker.

So "112" is smaller than "2"

---

Sorting gets even more fun when you mix numbers and strings.

How would you sort [1, 2, 12, "2b", "2", "a"] ?

---

So does Javascript have a natsort?

lol of course not, but there's an NPM package https://www.npmjs.com/package/natsort

Please use

Your users will thank you and your UI will be better :)

Originally published at twitter.com

contact: email - twitter / Terms / Privacy