在Ramda.js中分组和求和

时间:2014-11-30 14:43:50

标签: javascript ramda.js

我有两个名单:

var listA = 
[
    { Id: 2, Date: "2014-11-28", Amount: 30 },
    { Id: 1, Date: "2014-11-27", Amount: 15 },
    { Id: 1, Date: "2014-11-28", Amount: 20 },
];

var listB = 
[
    { Id: 1, Date: "2014-11-27", Amount: 15 },
    { Id: 2, Date: "2014-11-26", Amount: 25 },
];

我希望合并两个列表中的数据,按ID对其进行分组,并使用结果中每个Id的最高日期,并对唯一对象的总数进行求和(即具有相同Id和日期的对象 - 可以每个日期只有一个金额和Id)。

换句话说,我想要这个结果:

// "For ID X, the Amounts up to Date Y = total Z"
[
    {"Id":1,"Date":"2014-11-28","Amount":35},
    {"Id":2,"Date":"2014-11-28","Amount":55}
]

我对Ramda很新,但我已设法使用此代码合并列表:

// Helper functions to build predicate list
var predicateListFunc = function (props) { return R.allPredicates(R.map(R.curry(R.eqProps), props)); }
var compareProperties = R.unapply(predicateListFunc);

// Function to merge lists based on object Ids and Dates
var mergeLists = R.unionWith(compareProperties("Id", "Date"));

// Function to sort in date descending order; used later to facilitate grouping
var sortByDateDesc = R.compose(R.reverse, R.sortBy(R.prop("Date")));

// Merge the lists
var mergedData = sortByDateDesc(mergeLists(listA, listB));

用于分组和总结:

// My original code used a side-effect because I could not get the R.reduce to 
// work.  Turns out it was a typo that prevented the initial list from propagating
// correctly.  I reimplemented it and spotted the typo after reading Furqan Zafar's 
// comment)
var groupCalc = function (list, item) {
    var index = R.findIndex(R.propEq("Id", item.Id), list);
    if (index >= 0) {
        list[index].Amount += item.Amount;
    } else 
        list.push(item); 

    return list;
};

var groupedList = R.reduce(groupCalc, [], mergedData);

虽然看起来确实有效,但我想知道在Ramda中解决这个问题的方法是否更好? groupBy的文档表明它在这里没用。

更新版本:jsFiddle

2 个答案:

答案 0 :(得分:4)

这是一个使用R.reduce函数避免副作用的小提琴:http://jsfiddle.net/013kjv54/6/

我只用以下内容替换了您的分组代码:

var result = R.reduce(function(acc, tuple){
    acc.push({
        StockId: tuple[0],                
        Reference: R.maxBy(function(record){return new Date(record.Reference)}, tuple[1]).Reference,
        Amount: R.reduce(function(acc, record){return acc + record.Amount}, 0, tuple[1])
    });
    return acc;
}, [], R.toPairs(R.groupBy(function(record){return record.StockId})(mergedData)));

答案 1 :(得分:4)

当问到这个问题时,我没有看到这个。如果您仍然对替代方法感兴趣,则执行此操作的方式略有不同:

var combine = function(acc, entry) {
    return {
        Id: entry.Id, 
        Date: acc.Date && acc.Date > entry.Date ? acc.Date : entry.Date, 
        Amount: (acc.Amount || 0) + entry.Amount
    };
};

var process = R.pipe(
    R.groupBy(R.prop('Id')), 
    R.values, 
    R.map(R.uniqWith(R.eqProps('Date'))), 
    R.map(R.reduce(combine, {}))
);

var result = process(R.concat(listA, listB));

您可以在 JSFiddle 上看到它。与许多此类方法一样,它存在一个潜在的问题,即结果的顺序与底层JS引擎如何命令其对象关键参数有关,尽管这在现代引擎中大多是一致的。