javascript - Underscore JS: get 5 items per category -
i have 5 items per category. let's have array this:
[ {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"} ]
of each supplier have first 5 products. don't have clue how that. has?
my current code:
var formattedproducts = _(products).map( function( product ) { var pr = product.datavalues; var endtime = pr.end_datetime; return pr; });
this works me
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) first group elements according supplier.
2) each group first 5 elements & con-cat 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);
Comments
Post a Comment