有没有一种方法可以将reduce应用于两个数组,但不能在两次调用之间重置累加器?

时间:2018-09-06 19:04:19

标签: javascript arrays performance

所以,如果我有一个对象数组:

var synched = [{
   name = "something",
   value = 11132
}, {
   name = "something else",
   value = 1231233
}...]

和另一个几乎相同但包含一些其他值的数组:

var opened = [{
   name = "something",
   value = 1233312
}, {
   name = "something else",
   value = 12312333
}, {
   name = "something",
   value = 1241233

}]

我想将它们全部合并成一个对象数组,在其中我计算两个数组中“名称”的总准确度。

var result = [{
    name: "something",
    opened: 2,
    synched: 1,
    total: 3
}, {
    name: "something else",
    opened: 1,
    synched: 1,
    total: 2
}]

是否有比进行多个array.reduce调用更有效的方式?

var data = synched.reduce(function (data, item) {
    var key = item.name
    var created = (data[key] || (data[key] = {'name': key, 'opened': 0, 'synched': 0, 'total': 0}));
    created['synched'] += 1;
    created['total'] += 1;

    return data;
}, {});

var data1 = opened.reduce(function (data1, item) {
    var key = item.name
    var created = (data1[key] || (data1[key] = {'name': key, 'opened': 0, 'synched': 0, 'total': 0}));
    created['opened'] += 1;
    created['total'] += 1;

    return data1;
}, {});

Object.keys(data).forEach(function (key) {
    if(data1.hasOwnProperty(key)){
        data1[key]['synched'] = data[key]['synched'];
        data1[key]['total'] = data[key]['total'] + data1[key]['total'];
    } else {
        data1[key] = data[key];
    }
});

var result = Object.keys(data1).map(function(item) { return data1[item]; });

编辑:

按照@Pointy的建议,我可以这样做:

var data1 = opened.reduce(function (data, item) {
        var key = item.name
        var created = (data[key] || (data[key] = {'name': key, 'opened': 0, 'synched': 0, 'total': 0}));
        created['opened'] += 1;
        created['total'] += 1;

        return data;
    }, data);

,这将使我摆脱第三次迭代。谢谢!

0 个答案:

没有答案