[英]how to loop through array of arrays and combine values
I need to loop through a array of arrays and calculate the sum of each array. 我需要遍历数组数组并计算每个数组的总和。 The Json is a kendo-ui chart series with arrays of x,y coordinates.
Json是具有x,y坐标数组的kendo-ui图表系列。 I need to return the sum of the x,y values.
我需要返回x,y值的总和。 linq.js or javascript will work.
linq.js或javascript都可以。 thanks JSON
感谢JSON
var =series = [{
"style":"smooth",
"color":"blue",
"data":[
[600,30000],
[800,60000],
[1100,100000]
],
"name":"Subject Property",
"removeByNames":[
["Product1"],
["Product2"],
["Product3"]
],
"$$hashKey":"object:30"
}]
So for this example i would need to end up with this 所以对于这个例子,我将需要结束
var newSeries = [{
"style":"smooth",
"color":"blue",
"data":[
[30600],
[60800],
[101100]
],
"name":"Subject Property",
"removeByNames":[
["Product1"],
["Product2"],
["Product3"]
],
"$$hashKey":"object:30"
}]
for(var i=0;i<series[0].data.length;i++){
var val = series[0].data[i];
newSeries.data[i] = val[0] + val[1];
}
You can use loop and use reduce
您可以使用循环并使用
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;
});
}
}
Demo: http://jsfiddle.net/kv854c61/1/ 演示: http : //jsfiddle.net/kv854c61/1/
you just need to loop the values in your data properties something like this.. 您只需要像这样循环数据属性中的值即可。
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;
}
}
now it would make sense to add the new data array, so as not to overwrite 现在添加新的数据数组将很有意义,以免覆盖
series[i].new_data[j] = result;
Array.map
is quite useful in this case: 在这种情况下,
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]]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.