LoginSignup
1
1

More than 3 years have passed since last update.

「JSでStrCmpLogicalWみたいなソートがしたい」「 (╬▔皿▔)╯<ア”?」 ってなった時

Posted at

顧客「自然順にして」

言語やユーザ、OSによって解釈が分かれてくる「自然順」。
正直なコト言うと「JSではarr.sort() が自然順だ!運用回避でよろしく。」とか言いたい。

が、いい感じにソートを行ってくれるやつに遭遇した。

const natsort = new Intl.Collator(navigator.language, {sensitivity: 'variant', numeric:true}).compare;

文字列のリストを

a2sample
a10sample
b10sample1
b10sample10
b1sample1
b2sample1
b10sample2
b2sample2
b1sample2
b1sample10
b2sample10
a1sample

arr.sort(natsort) とかすることで

a1sample
a2sample
a10sample
b1sample1
b1sample2
b1sample10
b2sample1
b2sample2
b2sample10
b10sample1
b10sample2
b10sample10

いい感じにソートしてくれました。

参考: Intl.Collator - JavaScript|MDN

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1