2
2

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.

【JavaScript】多次元配列の並び替えをする(複数キーも想定)

Last updated at Posted at 2022-10-27

JavaScriptで多次元配列をソートする方法

以下の配列を想定

const lists = [ 
  [ 1, 3 ], 
  [ 1, 2 ], 
  [ 2, 1 ], 
  [ 1, 1 ] 
]

昇順

1つ目を第一優先

function sortArray(arr){
  arr.sort((a,b) => {
    return a[0] - b[0]
  })
}
sortArray(lists);

// 出力    
// [
//  [ 1, 3 ], 
//  [ 1, 2 ], 
//  [ 1, 1 ], 
//  [ 2, 1 ] 
// ]

2つ目を第一優先

function sortArray(arr){
  arr.sort((a,b) => {
    return a[1] - b[1]
  })
}
sortArray(lists);

// 出力    
// [
//  [ 2, 1 ], 
//  [ 1, 1 ], 
//  [ 1, 2 ], 
//  [ 1, 3 ] 
// ]

降順

1つ目を第一優先

function sortArray(arr){
  arr.sort((a,b) => {
    return b[0] - a[0]
  })
}
sortArray(lists);

// 出力    
// [
//  [ 2, 1 ], 
//  [ 1, 3 ], 
//  [ 1, 2 ], 
//  [ 1, 1 ] 
// ]

2つ目を第一優先

function sortArray(arr){
  arr.sort((a,b) => {
    return b[0] - a[0]
  })
}
sortArray(lists);

// 出力    
// [
//  [ 1, 3 ], 
//  [ 1, 2 ], 
//  [ 2, 1 ], 
//  [ 1, 1 ] 
// ]

複数キーの並び替え

1つ目を第一優先、2つ目を第二優先(いずれも昇順)

この場合、以下で出来た!!

function sortArray(arr){
  arr.sort((a,b) => {
    if (a[0] < b[0]) return -1
	if (a[0] > b[0]) return 1
	if (a[1] < b[1]) return -1
	if (a[1] > b[1]) return 1
    return 0
  })
}
    
// 出力    
// [
//  [ 1, 1 ], 
//  [ 1, 2 ], 
//  [ 1, 3 ], 
//  [ 2, 1 ] 
// ]

もっとスマートな書き方ありましたら教えてください。

参考

2
2
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
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?