【Underscore.js】_.groupByを読んだ
jashkenas/underscoreの_.groupByを読んだ。
概要
_.groupBy(list, iteratee, [context])
listの各要素をiterateeを使ってグルーピングする。 iterateeが関数でない場合は、そのプロパティの値ごとにグルーピングする。
var list = [ {age: 20, sex: "male", country: "JP", name: "hoge"}, {age: 22, sex: "male", country: "US", name: "fuga"}, {age: 20, sex: "female", country: "US", name: "piyo"}, {age: 45, sex: "male", country: "JP", name: "HUGA"}, {age: 20, sex: "male", country: "JP", name: "hoge"} ]; var x = _.groupBy(list, 'age'); console.log(x); // {20: [{age: 20, sex: "male", country: "JP", name: "hoge"},{age: 20, sex: "female", country: "US", name: "piyo"},{age: 20, sex: "male", country: "JP", name: "hoge"}], 22:[{age: 22, sex: "male", country: "US", name: "fuga"}], 45:[{age: 45, sex: "male", country: "JP", name: "HUGA"}]}
ソースコード
var group = function(behavior) { return function(obj, iteratee, context) { var result = {}; iteratee = cb(iteratee, context); _.each(obj, function(value, index) { var key = iteratee(value, index, obj); behavior(result, value, key); }); return result; }; }; // Groups the object's values by a criterion. Pass either a string attribute // to group by, or a function that returns the criterion. _.groupBy = group(function(result, value, key) { if (_.has(result, key)) result[key].push(value); else result[key] = [value]; });
listのそれぞれの要素にたいして、iterateeを実行して、その値をkeyとする。 その後、keyをプロパティとして結果の配列にpushする。 これを各要素分繰り返す。