Home > Back-end >  How to calculate the difference of two values that are present in sub arrays of an array with a loop
How to calculate the difference of two values that are present in sub arrays of an array with a loop

Time:12-17

I have an array of arrays where each sub-array holds two values each. The end goal here is calculate the decrease/increase of each sub-array so I can then calculate an overall average. In this case, I am trying to calculate the average month on month change to then work out a total average for the year.

let groupedMonthTotals = [
                          [867884, 984655],[322013, -69417], [310503, 522857],
                          [1033096, 604885],[-216386, 477532], [893810, -80353]
                         ];

Essentially, each sub-array represents two months, so in this case it's [Month 1, Month 2], [Month 3, Month 4] and so on. Once I have a figure for each sub array, I will then find the average as a number.

I have been able to calculate the following:

let test1 = groupedMonthTotals[0][1];
let test2 = groupedMonthTotals[1][1];
let difference = test2 - test1;

However, it's not feasible for me to manually run each index and child index as the data that I have spans for over 43 months. I have just provided a snapshot for this question.

How can I loop the following logic for it to spit out the difference? Ideally, I'd like to put these values into an array of their own.

CodePudding user response:

Map through the array:

let groupedMonthTotals=[[867884,984655],[322013,-69417],[310503,522857],[1033096,604885],[-216386,477532],[893810,-80353]];

const result = groupedMonthTotals.map(e => e[1] - e[0])
console.log(result)

  • Related