I have a project that requires me to add the values of multiple arrays, not necessarily all the same length.
I have 8 arrays that can be of varying lenght:
p1 = [1,5,6,8,3,8,]
p2 = [3,3,3,2,8,3,3,4]
p3 = [1,2,3,4,5,6,7,8,9]
p4 = [1,3,4,5,6,7,2,0,2,8,7]
and so on.
What I need to do is add the same key values together to make 1 'results' array, that would look something like:
results = [6, 13, 16, 19, 22, 24, 12, 12, 11, 8, 7]
I've found some code on Stackoverflow that does the job beautifully in most browsers, with the exception of IE8.
Javascript merge 2 arrays and sum same key values
Here is the code that works in most browsers:
var sums = {}; // will keep a map of number => sum
[p1, p2, p3, p4, p5, p6, p7, p8].forEach(function(array) {
//for each pair in that array
array.forEach(function(pair) {
// increase the appropriate sum
sums[pair[0]] = pair[1] + (sums[pair[0]] || 0);
});
});
// now transform the object sums back into an array of pairs, and put into array named 'results'...
var results = [];
for(var key in sums) {
results.push([key, sums[key]]);
}
The problem (I think) is that IE8 doesn't support forEach. Is there a way to do this without using forEach, either with plain Javascript or jQuery?