Aggregating values ​​of JavaScript array objects?

JavaScript defines n number of arrays as input in this format: (n = 2)

array1:
[{x: 1, y: 5},{x: 2, y: 3},{x: 3, y: 6}]

array2:
[{x: 1, y: 2},{x: 2, y: 6},{x: 3, y: 2}]

How to easily aggregate Y values ​​and get this resulting array:

arrayOutput:
[{x: 1, y: 7},{x: 2, y: 9},{x: 3, y: 8}]

Thank.

+3
source share
2 answers

Refresh . An additional comment about values xand their positions in arrays makes below unimportant.

There is no particular trick, you just scan the arrays and create your result. This is nothing more than a nested loop. If you are trying to make the most out of a wide range of JavaScript engines, avoid unnecessary function calls.

Something along the lines of:

function sumYValues(arrays) {
    var outer, inner, array, entry, sum, result, x;

    // Create our result array with a copy of the first array
    result = [];
    if (arrays.length > 0) {
        array = arrays[0];
        for (inner = 0; inner < array.length; ++inner) {
            entry = array[inner];
            result[inner] = {x: entry.x, y: entry.y};
        }

        // Add in the remaining values
        for (outer = 1; outer < arrays.length; ++outer) {
            array = arrays[outer];
            // You might want an assert here verifying that result.length == array.length
            for (inner = 0; inner < array.length; ++inner) {
                entry = array[inner];
                // You might want an assert here verifying that result[inner].x == entry.x
                result[inner].y += entry.y;
            }
        }
    }

    return result;
}

0 ( 1) array.length - 1. , (array.length - 1 0 ( 1)) , , "t22 > ". , , C, ( 0 , ), JavaScript.


, , .

x , , , , x , , . :.

function sumYValues(arrays) {
    var outer, inner, ar, entry, sum, result, x;

    sum = {};
    for (outer = 0; outer < arrays.length; ++outer) {
        ar = arrays[outer];
        for (inner = 0; inner < arrays.length; ++inner) {
            entry = ar[inner];
            sum[entry.x] = (sum[entry.x] || 0) + entry.y;
        }
    }

    result = [];
    for (x in sum) {
        result.push({x: x, y: sum[x]});
    }

    return result;
}

sum, , x = > y, .

:

            sum[entry.x] = (sum[entry.x] || 0) + entry.y;

sum x, sum[entry.x] undefined, "" . - || x sum 0, y .

+2

, , , native/underscore.

function createOutput(arr1, arr2, arr3 /*, ... */) {
    return Array.prototype.reduce.call(arguments, function (prev, curr) {
        return prev.map(function(val, index) {
            return {
                x: val.x,
                y: val.y + curr[index].y
            }
        });
    });
}

, x 1..n .

ES5. _, ​​ -.

function createOutput() {
    return _.reduce(arguments, function (memo, arr) {
        return _.map(memo, function(val, index) {
            return { x: val.x, y: val.y + arr[index].y };
        });
    });
}
+3

All Articles