累积求和/排序javascript

累积求和/排序javascript,javascript,d3.js,Javascript,D3.js,嗨,我有一个像这样的数组 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:

嗨,我有一个像这样的数组

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,但是我还没有找到一个很好的解决方案,计算出的总数没有保存在正确的对象上,可能是因为循环中的排序错误

所以,如果使用d3有一个干净的解决方案,我会非常高兴,因为如果我以后添加其他属性,我可以很容易地使用map或key

谢谢

编辑

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 })
}
var-calc=[];
var计数=0;
var newArr=data.sort(函数(a,b){
返回a.id-b.id;
})
对于(变量i=0;i
对于排序部分,我尝试了
a.id-b.id
b.id-a.id

这样做的一个问题是,它似乎没有按照我需要的顺序完成,使用这种方式,我没有简单的方法将其映射到d3.js,因此我更喜欢使用这种方式的解决方案

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;
});

发布您为尝试此操作而编写的代码,并解释哪些特定部分不起作用。欢迎访问。我们愿意帮助人们,只要我们看到他们已经实施了什么。。真的吗?是的!你最初的问题没有代码,你没有描述你试图做什么,你没有解释给你带来麻烦的具体部分-你所做的只是说“嘿,这是我想要的-我怎么做?”这是最广泛和最普遍的。