0

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

1 Answer 1

1

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);

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you a lot! This seems to be the best way to go! Give me 9 minutes to accept your answer!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.