1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

sort()メソッドで大文字と小文字を分けずにソートさせる方法

Posted at

タイトルの通りの備忘録です。

let a = ['Dog', 'cat', 'Bug', 'ant'];
a.sort(function (s, t) {
  let a = s.toLocaleLowerCase();
  let b = t.toLocaleLowerCase();
  if (a < b) return -1;
  if (a > b) return 1;
  return 0;
});
// a == ['ant', 'Bug', 'cat', 'Dog']

ソートの順序を変える場合は、sort()メソッドの引数に比較関数を指定する。この関数は引数を2つ取り、両者を比較する。第1引数を第2引数の前にしたければ関数から返す値をゼロより小さな値にする。前にしたければゼロより大きな値にする。2つの値が同じ場合は、関数から返す値を0にする。

参考記事

勉強本

1
0
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
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?