[英]Aggregating JavaScript array into several arrays with different element lengths?
I have an array with 101 values (representing people aged 0-100). 我有一个包含101个值的数组(代表0-100岁的人)。
What would be a preferably fast and simple way of building these aggregated arrays in one go: 一次性构建这些聚合数组的最佳方法是快速简便:
var input = [55,33,12 .. 98 more]
var output = {
//same as input
i1 = [],
//0-5, 6-10, 11-15 ... 96-100
i5 = [],
//0-10, 11-20, 21-30 ... 91-100
i10 = [],
//0-20, 21-40, 41-60 ... 81-100
i20 = [],
}
On a side note: Would you name these aggregate arrays by the interval ("i1", "i5") or by the number of groups/elements ("g100", "g20") - what is more intuitive if another programmers comes across these definitions? 附带说明一下:您是用间隔(“ i1”,“ i5”)还是组/元素的数量(“ g100”,“ g20”)来命名这些聚合数组-如果遇到其他程序员,这会更直观这些定义?
You can reuse results of the aggregation to calculate the next array. 您可以重用聚合结果来计算下一个数组。
// sums up each n numbers from the input array
//
function groupSum(inarray, n) {
var outarray = [];
var sum = 0;
for (var i = 0; i < inarray.length; i++) {
sum += inarray[i];
if (i % n == n - 1) {outarray.push(sum); sum = 0;}
}
// add the last element
if (i % n != 0) { outarray.push(sum); }
return outarray;
}
var input = [55, 33, 12, 98, /* more numbers here */ 3, 4, 1, 2, 0, 7];
var output = {};
output.i1 = input;
output.i5 = groupSum(output.i1, 5);
output.i10 = groupSum(output.i5, 2);
output.i20 = groupSum(output.i10, 2);
Note that, as xanatos said, performance is not really of big concern here. 请注意,正如xanatos所说,在这里性能并不是真正的大问题。
PS1: was not sure if you were trying to make output an object (as in this code) or 2D array. PS1:不确定是否要使输出成为对象(如此代码中所示)或2D数组。
PS2: since your first group always has 1 more element, you might need to adjust the code a bit for this special case. PS2:由于您的第一组总是有1个以上的元素,因此对于这种特殊情况,您可能需要稍微调整一下代码。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.