简体   繁体   中英

Aggregating JavaScript array into several arrays with different element lengths?

I have an array with 101 values (representing people aged 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?

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.

PS1: was not sure if you were trying to make output an object (as in this code) or 2D array.

PS2: since your first group always has 1 more element, you might need to adjust the code a bit for this special case.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM