Underscore JS:每个类别获得5个项目

时间:2014-08-18 14:22:41

标签: javascript underscore.js

我想每个类别只有5个项目。假设我有一个这样的数组:

[
  {product_name: "test", supplier: "1"}
  {product_name: "test", supplier: "1"}
  {product_name: "test", supplier: "1"}
  {product_name: "test", supplier: "1"}
  {product_name: "test", supplier: "1"}
  {product_name: "test", supplier: "1"}
  {product_name: "test", supplier: "2"}
  {product_name: "test", supplier: "2"}
  {product_name: "test", supplier: "2"}
  {product_name: "test", supplier: "3"}
  {product_name: "test", supplier: "3"}
  {product_name: "test", supplier: "3"}
  {product_name: "test", supplier: "3"}  
]

在每个供应商中,我希望拥有前5个产品。 我不知道该怎么做。有人吗?

我目前的代码:

var formattedProducts = _(products).map( function( product ) {

    var pr =  product.dataValues;
    var endTime = pr.end_datetime;

    return pr;
});

2 个答案:

答案 0 :(得分:2)

这对我有用

var data = [
  {product_name: "test", supplier: "1"},
  {product_name: "test", supplier: "1"},
  {product_name: "test", supplier: "1"},
  {product_name: "test", supplier: "1"},
  {product_name: "test", supplier: "1"},
  {product_name: "test", supplier: "1"},
  {product_name: "test", supplier: "2"},
  {product_name: "test", supplier: "2"},
  {product_name: "test", supplier: "2"},
  {product_name: "test", supplier: "3"},
  {product_name: "test", supplier: "3"},
  {product_name: "test", supplier: "3"},
  {product_name: "test", supplier: "3"}  
]

1)根据供应商的所有要素的第一组。

2)让每个小组获得他们的前5个元素& con-cat to result array。

var result = [];
var groups = _.groupBy(data,function (item) {
    return item.supplier;
}); 

_.each(groups,function(value){
    result = result.concat(_.first(value,5));
})

console.log(result);

DEMO

答案 1 :(得分:0)

只是为了好玩,这是一个Lo-Dash链式样式。

var result = _(products)
    .groupBy('supplier')
    .map(function (productsBySupplier) {
        return _.first(productsBySupplier, 5)
    })
    .flatten()
    .value()