JavaScript
Node.js

配列内の特定のオブジェクトのキーでソートする

More than 3 years have passed since last update.

本来なら、lo-dash使いたいけど、手元の環境ですぐに利用できる環境が以下だったのでそちらで試した内容をまとめておきます

  • 環境
    • node v0.12.0
    • Underscore.js 1.6.0

対象となるJSONのデーター構造

WebAPIから取得するJSONみたいなものを想定しています

var posts = [
  {"created_at": "2015-08-10T13:28:59.000+09:00","name": "test1", "picutre": "sample1.jpg" },
  {"created_at": "2015-08-20T13:28:59.000+09:00","name": "test3", "picture": "sample3.png" },
  {"created_at": "2015-08-01T13:28:59.000+09:00","name": "test0", "picture": "sample4.png" },
  {"created_at": "2015-08-15T13:28:59.000+09:00","name": "test2", "picture": "sample2.png" }
]

特定のキーでソートする

名前順でソートするにはこんな感じ

var posts,
    result_name,
    sorby_by_create_at;
_ = require('underscore');
posts = [
  {"created_at": "2015-08-10T13:28:59.000+09:00","name": "test1", "picutre": "sample1.jpg" },
  {"created_at": "2015-08-20T13:28:59.000+09:00","name": "test3", "picture": "sample3.png" },
  {"created_at": "2015-08-01T13:28:59.000+09:00","name": "test0", "picture": "sample4.png" },
  {"created_at": "2015-08-15T13:28:59.000+09:00","name": "test2", "picture": "sample2.png" }
]

result_name = _.sortBy(posts, function (post) { return post.name; });

日付順でソートするにはこんな感じ

var posts,
    result_name,
    sorby_by_create_at;
_ = require('underscore');
posts = [
  {"created_at": "2015-08-10T13:28:59.000+09:00","name": "test1", "picutre": "sample1.jpg" },
  {"created_at": "2015-08-20T13:28:59.000+09:00","name": "test3", "picture": "sample3.png" },
  {"created_at": "2015-08-01T13:28:59.000+09:00","name": "test0", "picture": "sample4.png" },
  {"created_at": "2015-08-15T13:28:59.000+09:00","name": "test2", "picture": "sample2.png" }
]
sorby_by_created_at = _.sortBy(posts, function (post) { return post.created_at; });

日付を最新の順番に並べ替えるのなら、sortByした後にreverse()すればOK

var posts,
    result_name,
    sorby_by_create_at;
_ = require('underscore');
posts = [
  {"created_at": "2015-08-10T13:28:59.000+09:00","name": "test1", "picutre": "sample1.jpg" },
  {"created_at": "2015-08-20T13:28:59.000+09:00","name": "test3", "picture": "sample3.png" },
  {"created_at": "2015-08-01T13:28:59.000+09:00","name": "test0", "picture": "sample4.png" },
  {"created_at": "2015-08-15T13:28:59.000+09:00","name": "test2", "picture": "sample2.png" }
]
sorby_by_created_at = _.sortBy(posts, function (post) { return post.created_at; });
sorby_by_created_at.reverse();