2
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 3 years have passed since last update.

[JavaScript] sort()の使い方

Posted at

文字列のソートにsort()を使用したので使い方と合わせて数値のソートについてもまとめておく。

sort()の使い方

このsort()は、配列の要素を順番に並び替えてくれるメソッド。このメソッドは、配列の要素を文字列に変換してから比較を行い、昇順にソートされる。そのため、文字列を比較する場合は次のように書ける。

array = ["red", "white", "blue", "green", "black"];
array.sort();    // [ 'black', 'blue', 'green', 'red', 'white' ]

ここで、ソートされた結果は元の配列(上記だとarray)に上書きされるので、元の配列データは変更されてしまうことに注意が必要である。元の配列のデータを保持しておきたい場合は、あらかじめ配列をコピーしておく必要がある。

数値の比較の場合

上記のように文字列の比較はそのままメソッドを使用すればよいが、数値を比較する場合は比較関数を指定して記述する。比較関数はアロー関数(ラムダ式)を使って書くこともできる。一次元配列の数値のソートを行う場合は以下のように書ける。

// 昇順ソート
array = [130, 90, 30, 7, 50];
array.sort((a,b) => a - b);    // [ 7, 30, 50, 90, 130 ]

// 降順ソート
array = [130, 90, 30, 7, 50];
array.sort((a,b) => b - a);    // [ 130, 90, 50, 30, 7 ]
2
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
2
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?