使用下划线计数和总数组元素

时间:2015-05-12 07:49:10

标签: underscore.js

假设我有两个JavaScript数组:

var types = ["w", "x", "y", "z"];

var data = [["x", 3], ["y", 4], ["x", 2], ["z", 6], ["z", 3], ["x", 1], ["z", 2]];

使用Underscore.js我想产生这两个结果:

var counts = [["w", 0], ["x", 3], ["y", 1], ["z", 3]];

var totals = [["w", 0], ["x", 6], ["y", 4], ["z", 11]];

counts数组只计算每个元素在数据数组中出现的实例数。 totals数组按类型汇总数据数组中出现的元素。即使类型数组中的元素没有出现在数据数组中,我也需要代码才能工作 - 因为在这种情况下,数据中没有“w”元素。

提前致谢。

2 个答案:

答案 0 :(得分:0)

我只是循环(下划线方式)

_navigateTo("http://myapp/login.html");
// login as first user
...
// launch a new browser instance
var $instanceId = _launchNewBrowser("http://myapp/login.html");
_wait(5000);
// wait and select the new browser instance using the instanceId
_selectBrowser($instanceId);
// log in as second user
// send a chat message to first user
...

// Select the base window
_selectBrowser();
// view chat window and verify second user's chat message has arrived
...

答案 1 :(得分:0)

您可以将data数组转换为包含不同结果的结构:

var res = {};
_.each(data, function(item) {
    var r = res[item[0]] = res[item[0]] || {total: 0, nb: 0};
    r.nb++;
    r.total+= item[1];
});

会给你

res = {
    x: {total:6, nb:3},
    y: {total:4, nb:1},
    z: {total:11, nb:3}
}

然后映射您的types数组以提取所需的格式:

var counts = _.map(types, function(t) {
    return [t, res[t] && res[t].nb || 0];
});

var totals = _.map(types, function(t) {
    return [t, res[t] && res[t].total || 0];
});

演示http://jsfiddle.net/nikoshr/wmo7br0u/