1

現在、ハッシュの配列を含む JSON ファイルがあり、一致するキー「Club」ごとにハッシュの配列を返すことができるようにしたいと考えています。

  [
    {"Bookmaker": "First", "Club": "Man City", "Decimal": 3.65},
    {"Bookmaker": "First", "Club": "Man Utd", "Decimal": 4.5},
    {"Bookmaker": "First", "Club": "Chelsea", "Decimal": 6.8}
    {"Bookmaker": "Second", "Club": "Man City", "Decimal": 3.5},
    {"Bookmaker": "Second", "Club": "Man Utd", "Decimal": 4},
    {"Bookmaker": "Second", "Club": "Chelsea", "Decimal": 7}
  ]

この例では、返される配列は次のようになります。

[
 {"Bookmaker": "First", "Club": "Man City", "Decimal": 3.65},
 {"Bookmaker": "First", "Club": "Man Utd", "Decimal": 4.5},
 {"Bookmaker": "Second", "Club": "Chelsea", "Decimal": 7}
]

各「クラブ」の「10 進」値が最も高いハッシュを返します。

4

3 に答える 3

1

結果セットにグレーター値が見つかった場合は、ハッシュ テーブルを使用して結果を変更できます。

var data = [{ "Bookmaker": "First", "Club": "Man City", "Decimal": 3.65 }, { "Bookmaker": "First", "Club": "Man Utd", "Decimal": 4.5 }, { "Bookmaker": "First", "Club": "Chelsea", "Decimal": 6.8 }, { "Bookmaker": "Second", "Club": "Man City", "Decimal": 3.5 }, { "Bookmaker": "Second", "Club": "Man Utd", "Decimal": 4 }, { "Bookmaker": "Second", "Club": "Chelsea", "Decimal": 7 }],
    result = [];

data.forEach(function (a) {
    if (a.Club in this) {
        if (result[this[a.Club]].Decimal < a.Decimal) {
            result[this[a.Club]] = a;
        }
        return;
    }
    this[a.Club] = result.push(a) - 1;
}, Object.create(null));

console.log(result);

于 2016-07-28T19:25:32.853 に答える
0

アンダースコアのようなライブラリにアクセスできる場合は、問題をいくつかの連鎖呼び出しに単純化できます。

var list = [
  {"Bookmaker": "First", "Club": "Man City", "Decimal": 3.65},
  {"Bookmaker": "First", "Club": "Man Utd", "Decimal": 4.5},
  {"Bookmaker": "First", "Club": "Chelsea", "Decimal": 6.8},
  {"Bookmaker": "Second", "Club": "Man City", "Decimal": 3.5},
  {"Bookmaker": "Second", "Club": "Man Utd", "Decimal": 4},
  {"Bookmaker": "Second", "Club": "Chelsea", "Decimal": 7}
];

var maxes = [];

_.chain(list)
  .groupBy(function( obj ) { return obj.Club; })
  .each(function( groupedList ) {        
    maxes.push(_.max(groupedList, function( item ) {
      return item.Decimal;
    }));
  });

// maxes array will now have the three objects with the highest Decimal
于 2016-07-28T19:54:35.037 に答える