2017-02-12 313 views
0

我有一個數組,我希望獲取唯一值和它們出現的次數,並總結匹配的公司名稱。我正在使用lodash,到目前爲止,我可以獲得每個獨特的價值。使用lodash獲取數組中唯一的值,總計和數量

我怎樣纔能有效地得到每個事件的數量,並將它們相加?價格數據是字符串。

var data = [ 
{"cat":"IT","company":"Apple", "price":"100.5"}, 
{"cat":"IT","company":"Apple", "price":"100"}, 
{"cat":"IT","company":"Google", "price": "100"}, 
{"cat":"IT","company":"Apple", "price": "100"} 
]; 

結果我需要:

Company | Count | Sum 
Apple | 3 | 300.5 
Google | 1 | 100 

我迄今爲止代碼:

var result = _.map(_.uniqBy(data, 'company'), function (item) { 
    $('table').append('<tr><td>'+item.company+'</td></tr>'); 
}); 

是否有可能做的總和,並且在同一_.map功能裏面算什麼?

回答

0

下面是使用mapValues一個可能lodash解決方案,首先groups由公司的組,然後映射到彙總對象:

// return the price of an item as a number 
var getPrice = function(item){ 
    return _.toNumber(item.price); 
} 

// convert a group of items into a summary object 
var groupToSummary = function(group){ 
    return { 
     count: group.length, 
     sum: _.sumBy(group, getPrice) 
    } 
} 

// perform the transformation 
var result = _(data) 
    .groupBy('company') 
    .mapValues(groupToSummary) 
    .value(); 

最終的目標是這樣的:

{ 
    Apple: { count: 3, sum: 300.5 }, 
    Google: { count: 1, sum: 100 } 
} 

它可以使用ES6箭頭函數可以縮短一點點,但是我已經使用胖函數離開它,因爲代碼中的代碼沒有使用任何ES6功能。

+0

這很好,謝謝先生! –

0

您可以先groupBy公司,然後mapreduce返回每個公司的對象數組。

var data = [ 
 
{"cat":"IT","company":"Apple", "price":"100.5"}, 
 
{"cat":"IT","company":"Apple", "price":"100"}, 
 
{"cat":"IT","company":"Google", "price": "100"}, 
 
{"cat":"IT","company":"Apple", "price": "100"} 
 
]; 
 

 
var group = _.groupBy(data, 'company') 
 

 
var result = _.map(_.keys(group), function(e) { 
 
    return _.reduce(group[e], function(r, o) { 
 
    return r.count += +o.price, r 
 
    }, {Company: e, count: 0, sum: group[e].length}) 
 
}) 
 

 
console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.15.0/lodash.min.js"></script>

0

使用純JSEcmascript5)溶液Array.prototype.reduce()Object.keys()功能:

var data = [ 
 
{"cat":"IT","company":"Apple", "price":"100.5"}, 
 
{"cat":"IT","company":"Apple", "price":"100"}, 
 
{"cat":"IT","company":"Google", "price": "100"}, 
 
{"cat":"IT","company":"Apple", "price": "100"} 
 
], rows = ""; 
 

 
var result = data.reduce(function(r, o) { 
 
    if (r[o.company]){ 
 
     ++r[o.company].count; 
 
     r[o.company].price += Number(o.price); 
 
    } else { 
 
     r[o.company] = {count: 1, price: Number(o.price)}; 
 
    } 
 
    return r; 
 
}, {}); 
 

 
Object.keys(result).forEach(function(name){ 
 
    rows += '<tr><td>'+ name +'</td>' + 
 
      '<td>'+ result[name].count +'</td>' + 
 
      '<td>'+ result[name].price +'</td></tr>'; 
 

 
}); 
 
$('table').append(rows);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<table> 
 
    <tr> 
 
    <th>Company</th> 
 
    <th>Count</th> 
 
    <th>Sum</th> 
 
    </tr>   
 
</table>