Sum of array

Hi,

I got 2 array variable and want make some calculation as below

var a = [“12”,“10”,“20”];
var b = [“2”,“1”];

So, how to plus var a based on var b?

For example above, var b = 2 then it will take value 12 and 10, and sum = 22
and then, var b= 1 will take value 20

Thanks in advance!

Could you explain the logic on a longer example?
Lets say

var a = [12, 10, 20, 5, 14, 10, 5];
var b = [2, 1, 3, 1];

Otherwise it isn’t that obvious what does “will take value 20” mean

Another question is what do you want to get in the result? An array of sums? Single total sum? Or what?

Just building slightly on @megazoid’s question a little, I’m interpreting var b as indicating the number of values the function you need has to add together (then return) from var a.

What var b doesn’t tell me though, is what index of the var a array, it is supposed to start at. Currently, there is an assumption that the function will start at index[0] and index[2], but it’s not explicitly stated anywhere.

Hi, sorry to make incomplete explanation, by referring through the @megazoid question, it will have as below end result:

[22]
[20]
[29]
[5]

meaning that by indicate the variable b,
var b = 2, it will take a[0]+a[1],
var b = 1, it will take a[2] value,
var b = 3, it will take a[3]+a[4]+a[5],
var b = 1, it will take a[6]

Thank you.

splice the first array defined by the lengths in the second array and then sum each of the chunks.

Done https://jsfiddle.net/6b7vt3L0/

2 Likes

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.