28
20

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

javascript ~ 二次元配列のソート~

Posted at

普通にsortメソッドを使ってて、そういえば二次元配列のsortとかどうするんだろって思ったのでまとめた。

ここで言う二次元配列のsortとは特定の深さにある要素でsortする時を想定。

普通の配列で昇順でsortするとき

var arr = [80, 40, 120];

arr.sort(function(a, b){
    return b - a;
});

=> [40, 80, 120]

これが普通のsortだけど二次元配列になった瞬間に10分ほどパニクった。

二次元配列の場合

var arr = [[6,2], [3,9], [1,7], [4,0], [8,5]]

array.sort(function(a,b){return(a[0] - b[0]);});

=> [1, 7],[3, 9],[4, 0],[6, 2],[8, 5]

array配列のindex[1]を基準にsortしたければreturnするデータのindexを指定してあげるだけ。

以上!

28
20
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
28
20

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?