Python 使用時の JSON ソートを書いたので、次は JavaScript
↓
oboe2uran.hatenablog.com
同様のJSONデータとする。
var data = { "title": "サンプル", "records": [ {"item": "item 2", "point": 74.68, "date":"2020-02-01" , "memo":"う" }, {"item": "item 1", "point": 4.63 , "date":"2020-02-02" , "memo":"あ" }, {"item": "item 3", "point": 9.38, "date":"2020-02-05" , "memo": null }, {"item": "item 4", "point": 5.78, "date":"2020-02-14" , "memo":"い" }, {"item": "item 5", "point": 5.53, "date":"2020-02-07" , "memo":"え" } ] };
日付の昇順
const sorted_records = data['records'].sort((a, b)=> a.date > b.date ? 1 : -1 );
pointの降順
const sorted_records = data['records'].sort((a, b)=> a.date > b.date ? -1 : 1 );
memo のソート、
null がある場合、やはり、そのままではソートできないので、'' 空文字でソートさせる必要がある。
const sorted_records = data['records'].sort((a, b)=>{ const c = a.memo==undefined ? "" : a.memo; const d = b.memo==undefined ? "" : b.memo; return c > d ? 1 : -1 }); data['records'] = sorted_records;
どうしても1行で済ませたいなら、括弧でくくる。
const sorted_records = data['records'].sort((a, b)=>(a.memo==undefined ? "" : a.memo) > (b.memo==undefined ? "" : b.memo) ? 1 : -1);