使用JavaScript在二维数组中添加值

时间:2015-08-30 00:20:39

标签: javascript

我想合并并添加以下2D数组:

var arr = [
    ["TWENTY", 20],
    ["TWENTY", 20],
    ["TWENTY", 20],
    ["TWENTY", 20],
    ["TEN", 10],
    ["FIVE", 5],
    ["ONE", 1],
    ["QUARTER", 0.25],
    ["QUARTER", 0.25],
    ["DIME", 0.1],
    ["DIME", 0.1],
    ["PENNY", 0.01],
    ["PENNY", 0.01],
    ["PENNY", 0.01],
    ["PENNY", 0.01]
    ];

产生如下所示的2D数组:

 arr = [
     ["TWENTY", 80],
     ["TEN", 10],
     ["FIVE", 5],
     ["QUARTER", 0.50],
     ["DIME", 0.20],
     ["PENNY", 0.04]
     ];

基本上我将数值加起来并压缩字符串值。我尝试了map,reduce和for循环,但这个让我难过。

2 个答案:

答案 0 :(得分:2)

你有一个包含key, value元组的数组。您可以遍历这些元组,将每个新密钥存储在一个对象中,并在后续元组使用相同的密钥时增加该值。如果按照遇到它们的顺序保留一组键,则可以将键数组映射到结果数组。

但是当你能够使用Nit的回答中所显示的纯粹功能性方法时,解决所有这些麻烦是愚蠢的。

以下是丑陋的方法。不要这样做。做Nit所说的。



function addArray(tuples) {
  var hash = {},
      keys = [];
  tuples.forEach(function (tuple) { // Iterate over [key, value] tuples.
    var key = tuple[0],
        value = tuple[1];
    if (hash[key] === undefined) {  // Is it a new key?
      keys.push(key);               // Then add it to keys.
      hash[key] = value;            // And set the initial value.
    } else {
      hash[key] += value;           // Otherwise, increment the value.
    }
  });
  return keys.map(function (key) {  // Map the keys to tuples.
    return([key, hash[key]]);
  });
};

var arr = [
    ["TWENTY", 20],
    ["TWENTY", 20],
    ["TWENTY", 20],
    ["TWENTY", 20],
    ["TEN", 10],
    ["FIVE", 5],
    ["ONE", 1],
    ["QUARTER", 0.25],
    ["QUARTER", 0.25],
    ["DIME", 0.1],
    ["DIME", 0.1],
    ["PENNY", 0.01],
    ["PENNY", 0.01],
    ["PENNY", 0.01],
    ["PENNY", 0.01]
];

var added = addArray(arr);

added.forEach(function (tuple) {
  document.write(JSON.stringify(tuple) + '<br />');
});
&#13;
&#13;
&#13;

答案 1 :(得分:1)

你真正需要的只是一个简化和地图,这可能会加起来很好的MapReduce笑话。

var arr = [
    ["TWENTY", 20],
    ["TWENTY", 20],
    ["TWENTY", 20],
    ["TWENTY", 20],
    ["TEN", 10],
    ["FIVE", 5],
    ["ONE", 1],
    ["QUARTER", 0.25],
    ["QUARTER", 0.25],
    ["DIME", 0.1],
    ["DIME", 0.1],
    ["PENNY", 0.01],
    ["PENNY", 0.01],
    ["PENNY", 0.01],
    ["PENNY", 0.01]
];
var obj = arr.reduce(function (out, el) {
    out[el[0]] = (out[el[0]] || 0) + el[1];
    return out;
}, {});
var out = Object.keys(obj).map(function (key) {
    return [key, obj[key]]
}); //[["TWENTY",80],["TEN",10],["FIVE",5],["ONE",1],["QUARTER",0.5],["DIME",0.2],["PENNY",0.04]]