簡體   English   中英

Javascript:按鍵求和多個數組的最有效方法

[英]Javascript: Most Efficient Way of Summing Multiple Arrays by Key

我有一個從Web服務返回的JSON對象,它是一個對象數組。 我需要將“數據”數組加在一起以形成一個求和數組。 JSON響應如下所示:

[  
  {  
    "data":[  
       0,3,8,2,5
    ],
    "someKey":"someValue"
  },
  {  
    "data":[  
       3,13,1,0,5
    ],
    "someKey":"someOtherValue"
  }
]

數組中可能有N個對象。 上面示例的期望輸出為:

[3, 16, 9, 2, 10]

我打算創建一個空的數組變量(var arr),然后遍歷對象,對於每個對象,遍歷“數據”鍵,對於每個鍵,將arr中的對應鍵增加一個值。

使用某種合並功能是否有更有效的方法?

怎么樣,我相信它應該適用於所有情況。

 var data = [{ "data": [ 0, 3, 8, 2, 5 ], "someKey": "someValue" }, { "data": [ 3, 13, 1, 0, 5 ], "someKey": "someOtherValue" }]; var datas = data.reduce(function(a, b) { b.data.forEach(function(x, i) { a[i] = a[i] || 0; a[i] += x; }); return a; }, []); console.log(datas); 

如果每個對象的data長度都相同,則可以嘗試:

var input; // Your input data
var output = [];
for (var i = 0; i < input[0].data.length; i++) {
  output[i] = input.reduce(function(prev, item) {
    return +(item.data[i]) + prev;
  }, 0);
}

console.log(output);
// [3, 16, 9, 2, 10]

如果每個對象的data大小都不同:

var input; // Your input data
var i = 0, output = [];
while (true) {
  var outOfIndex = true;

  var sum = input.reduce(function(prev, item) {
    if (item.data[i] !== undefined) {
      outOfIndex = false;
    }
    return +(item.data[i]) + prev;
  }, 0);

  if (outOfIndex) {
    break;
  }
  output[i++] = sum;
}

console.log(output);
// [3, 16, 9, 2, 10]

不太必要的解決方案:

//zip takes two arrays and combines them per the fn argument
function zip(left, right, fn) {
   var shorter = (right.length > left.length) ? left : right;
   return shorter.map(function(value, i) {
       return fn(left[i], right[i]);
   });
}

//assuming arr is your array of objects. Because were using
//zip, map, and reduce, it doesn't matter if the length of the
//data array changes
var sums = arr
    .map(function(obj) { return obj.data; })
    .reduce(function(accum, array) {

        //here we want to combine the running totals w/the current data
        return zip(accum, array, function(l, r) { return l + r; });
    });

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM