0

我需要遍历数组数组并计算每个数组的总和。Json 是一个带有 x,y 坐标数组的 kendo-ui 图表系列。我需要返回 x,y 值的总和。linq.js 或 javascript 将工作。感谢 JSON

var =series = [{
"style":"smooth",
"color":"blue",
"data":[
    [600,30000],
    [800,60000],
    [1100,100000]
],
"name":"Subject Property",
"removeByNames":[
    ["Product1"],
    ["Product2"],
    ["Product3"]
],
 "$$hashKey":"object:30"
}]

所以对于这个例子,我需要结束这个

var newSeries = [{
"style":"smooth",
"color":"blue",
"data":[
    [30600],
    [60800],
    [101100]
],
"name":"Subject Property",
"removeByNames":[
    ["Product1"],
    ["Product2"],
    ["Product3"]
],
"$$hashKey":"object:30"
}]
4

4 回答 4

3
for(var i=0;i<series[0].data.length;i++){
   var val = series[0].data[i];
   newSeries.data[i] = val[0] + val[1];
}
于 2015-05-27T14:45:02.217 回答
1

您可以使用循环并使用reduce

var series = [{
            ...
}]

for (var i = 0; i < series.length; i++) {
    for (var j = 0; j < series[i].data.length; j++) {
        series[i].data[j] = series[i].data[j].reduce(function(p,c) {
            return p + c;
        });
    }
}

演示:http: //jsfiddle.net/kv854c61/1/

于 2015-05-27T14:45:30.817 回答
1

你只需要像这样循环数据属性中的值..

for( var i - 0; i < series.length-1; i++){
  for( var j - 0; j < series[i].data.length-1; i++){
    var result = series[i].data[j][0] + series[i].data[j][1];
    series[i].data[j] = result;
  }
}

现在添加新的数据数组是有意义的,以免覆盖

series[i].new_data[j] = result;
于 2015-05-27T14:53:07.250 回答
1

Array.map在这种情况下非常有用:

// extracts the data entries of each item in the series
var data = series.map(function(item){ return item["data"]; });

function sum(point) {
    return point[0] + point[1];

    // in case point is of arbitrary dimension use Array.reduce:
    // return point.reduce(function(prev, cur){ return prev + cur; }, 0);
}

var sums = data.map(function(arr){
    return arr.map(function(point){
        return sum(point);
    });
});

// sums now contains an array of array of sums
// e.g. [[30600,60800,101100]]
于 2015-05-27T14:59:37.493 回答