累积求和/排序 JavaScript

cumulative summing/sorting javascript

本文关键字:排序 JavaScript 求和      更新时间:2023-09-26

嗨,我有一个看起来像这样的数组。

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 或键。

谢谢。

编辑

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所以我更喜欢使用它的解决方案。

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

小提琴