2015-10-13 35 views
-1

嗨,我有一個看起來像這樣的數組。累計求和/排序javascript

var data = [ 
    {beb: 200, cre: 0, id: 'A1'}, 
    {beb: 0, cre: 200, id: 'A2'}, 
    {beb: 0, cre: 100, id: 'A4'}, 
    {beb: 0, cre: 100, id: 'A3'}, 
] 

我該如何讓它看起來像這樣?

var newData = [ 
    {deb: 200, cre: 0, total: 200, id: 'A1'}, 
    {deb: 0, cre: 200, total: 0, id: 'A2'}, 
    {deb: 0, cre: 100, total: -100, id: 'A3'}, 
    {deb: 0, cre: 100, total: -200, id: 'A4'}, 
] 

最重要的是,數組首先需要對ID進行排序,然後將總量上的deb計算 - CRE +上一行總。

我目前使用D3在我的設置,但我一直沒能找到一個很好的解決方案,計算的總不得到保存正確的對象上,可能是因爲分揀GET的錯誤在循環中。

所以如果有一個乾淨的解決方案,使用D3我會很開心,因爲那樣我可以很容易地使用地圖或關鍵,如果我以後添加其他屬性。

謝謝。

編輯

var calc = []; 
var count = 0; 

var newArr = data.sort(function(a, b){ 
    return a.id - b.id; 
}) 

for(var i = 0; i < newArr.length; i++){ 
    var item = newArr[i]; 
    count += item.deb - item.cred 
    calc.push({deb: item.deb, cre: item.deb, total: count, id: item.id }) 
} 

因爲我曾經嘗試都a.id - b.idb.id - a.id

一個問題,這個排序的部分是,它似乎並沒有在我需要的順序來完成,使用這種方式,我沒有簡單的方法將它與d3.js進行映射,所以我更喜歡使用它的解決方案。

+0

帖子你寫嘗試這一點,並解釋什麼具體的部分是不工作的代碼。 – csmckelvey

+0

歡迎來到http://stackoverflow.com。我們喜歡幫助人們提供我們看到他們已經實施了什麼 –

+0

downvotes ..真的嗎? – Stellan

回答

2
data = data.sort(function(a, b) { 
    // to sort by number 
    // we need to get the number of the id first 
    // if the id will also change the part before the number this will have to be adjusted (just use the search) 
    var aid = parseInt(a.id.replace(/[^\d]/, ''), 10), 
     bid = parseInt(b.id.replace(/[^\d]/, ''), 10); 

    return aid - bid; 
}).map(function(d, idx, arr) { 
    // now we can calculate the total value 

    // previous data entry, or if it is the first round, a fake object 
    var previousData = (arr[idx - 1] || {"total": 0}); 

    // calc the total value 
    d.total = (d.beb - d.cre) + previousData.total; 
    return d; 
}); 

fiddle