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

連想配列を複数キーでソートする関数を作る関数

Posted at

入力によってソート基準が変わるような状況があったので探してもすぐ出てこなかったので作ってみた。
(ググり力が足りないのかもしれない)

 
 /*
  * keys: ソートキーの配列
  * order:  1:asc -1:desc
  */
 
 const genSortFunc = ( keys, order = 1 ) => (a, b) => {
   return keys 
     .map( key => {
     if (a[key] == b[key]) return 0
     
     return order * ( a[key] > b[key] ? 1 : -1 )
   })
   .find( o => o != 0) || 0
 }
 
 
 const array = [
   {name: 'a', key1: 1, key2: 1, key3: 1},
   {name: 'b', key1: 0, key2: 1, key3: 0},
   {name: 'c', key1: 1, key2: 0, key3: 0},
 ]
 
 console.log( array.sort(genSortFunc(['key1','key2'])))
 console.log( array.sort(genSortFunc(['key2','key3'])))
 console.log( array.sort(genSortFunc(['key1','key2'], -1)))

map.findしなくても、forEachで0(等価)以外が出たところで落としたほうが速いかも。

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