In JavaScript, given 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},{
Benchmark Example
Note that the mixed code is faster followed by loops followed by 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
}
});
});
}
Assumes arrays are sorted and contain all values of x in order 1..n with no gaps.
Kind of requires ES5. This can be swapped out for _ which gives this kind of functionality in a cross browser manner.
With underscore it is
function createOutput() {
return _.reduce(arguments, function (memo, arr) {
return _.map(memo, function(val, index) {
return { x: val.x, y: val.y + arr[index].y };
});
});
}