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},{x: 3, y: 2}]
How do I aggregate the Y-values easily and get this resulting array:
arrayOutput:
[{x: 1, y: 7},{x: 2, y: 9},{x: 3, y: 8}]
Thank you.
Benchmark Example
Note that the mixed code is faster followed by loops followed by native/underscore.
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
Update: The additional comment about the
x
values and their positions in the arrays makes the below irrelevant.There's no particular trick, you just loop through the arrays and build up your result. It's nothing more than a nested loop. If you're trying to be maximally efficient across a broad range of JavaScript engines, avoid unnecessary function calls.
Something along the lines of:
Those loops count from
0
(or1
) toarray.length - 1
. You might profile whether going backwards (array.length - 1
to0
(or 1)) is any faster, mostly the "down to0
" one. I used to assume it was because it was in C when I was a fresh-faced youth (comparisons to0
are faster than comparisons to another variable), but that assumption may or may not be valid in JavaScript.There's no particular shortcut, you just loop through the arrays, do your comparisons, and build up your result.
If the
x
values will be unique in each array, it may be easier to keep track of your ongoing sum by using an object rather than an array and usingx
values as keys, and then converting it into an array when you're done. E.g.:The above is mostly just to demonstrate using
sum
, an object, as a map ofx
=>y
values, although it does implement at least some of the summing logic as well.This line may need some explanation:
If
sum
doesn't have an entry for thatx
value,sum[entry.x]
will beundefined
, which is a "falsey" value. So we use the curiously-powerful||
operator to either get the value for thatx
fromsum
or0
, and then add the current entry'sy
to it and store the result.