简体   繁体   中英

Summing data in array of arrays in Javascript

I have the following array:

var myData = [
[7106.86000000, 5],
[7107.34000000, 2],
[7107.55000000, 10],
[7107.58000000, 3],
[7107.67000000, 90],
.....
]

I need to generate a new array where, on the second element of every row, i need to have the sum of the second element of the previous row, here is the desidered output:

var newData = [
[7106.86000000, 5],
[7107.34000000, 7],
[7107.55000000, 17],
[7107.58000000, 20],
[7107.67000000, 110],
.....
]

Since 5+2=7, 7+10=17 and so on.

Now i now how to do that with a normal array of elements, where i would have used reduce , but i don't know how to handle this with an array of arrays where i need to perform this operation only on the second element of every subarray. What can i use in this case? I was going to use a nested loop but it doesn't look like the most efficient way to do that, since this code will be executed on browser

Just take a closure over the sum and map the values while updating the sum with the right part.

 var data = [[7106.86000000, 5], [7107.34000000, 2], [7107.55000000, 10], [7107.58000000, 3], [7107.67000000, 90]], result = data.map((sum => ([l, r]) => [l, sum += r])(0)); console.log(result);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM