ikemonn's blog

技術ネタをちょこちょこと

【Underscore.js】_.sortByを読んだ

jashkenas/underscore_.sortByを読んだ。

概要

_.sortBy(list, iteratee, [context]

listの各要素をiterateeを使って評価した順にソートし、返す。 iterateeはプロパティの名前でも良い。

var list = [
    {age: 22, sex: "male", country: "US", name: "fuga"},
    {age: 45, sex: "male", country: "JP", name: "HUGA"},
    {age: 20, sex: "male", country: "JP", name: "hoge"}
];
var x = _.sortBy(list, 'age');
console.log(x); // [{age: 20, sex: "male", country: "JP", name: "hoge”},{age: 22, sex: "male", country: "US", name: "fuga"}, {age: 45, sex: "male", country: "JP", name: "HUGA"}]

ソースコード

  _.sortBy = function(obj, iteratee, context) {
    iteratee = cb(iteratee, context);
    return _.pluck(_.map(obj, function(value, index, list) {
      return {
        value: value,
        index: index,
        criteria: iteratee(value, index, list)
      };
    }).sort(function(left, right) {
      var a = left.criteria;
      var b = right.criteria;
      if (a !== b) {
        if (a > b || a === void 0) return 1;
        if (a < b || b === void 0) return -1;
      }
      return left.index - right.index;
    }), 'value');
  };

_.mapでvalue, index, iterateeを含むObjectを返す関数をlistの各要素に適用し、その値をソートする。 その後、pluckでvalueの値だけを取り出す。

.mapの引数である"value, index, list”は、.map内部の下記から来たもの。

results[index] = iteratee(obj[currentKey], currentKey, obj);

参考

jashkenas/underscore