Underscore [14] : 使用 groupBy 情境

摘要:Underscore 使用 filter 與 where 情境

在很多狀況下我們需要將資料做分組 , 就像在 SQL 裡面的 group by 功能一樣 , 

 

在 Underscore 裡面也有一個 groupBy 功能  , 其 API 使用如下 : 

 

_.groupBy([1.3, 2.1, 2.4], function(num){ return Math.floor(num); });
=> {1: [1.3], 2: [2.1, 2.4]}



_.groupBy(['one', 'two', 'three'], 'length');
=> {3: ["one", "two"], 5: ["three"]}

 

接下來我們來做個自己的範例 , 就拿前面所用過得範例來介紹 : 

 

接下來我們來針對 IsOverSea 屬性來做分組 , 

 

_.groupBy(funds,function(item){return item.IsOverSea;})

 

其結果如下 : 

 

see , 完美的幫我們分成 true 跟 false 兩組陣列嚕