Home > Software engineering >  Combine array of values with array of dates while averaging values for duplicate dates
Combine array of values with array of dates while averaging values for duplicate dates

Time:12-14

I can't work out the logic on this one, most of the other questions I've found have different data structures such as arrays of objects with duplicate keys.

I have two arrays of equal length - one is a list of values, the other is a corresponding date. For example:

values = [100,100,95,80,100,100,87,88,90,40];
dates = ['03 Dec', '03 Dec', '04 Dec', '04 Dec', '04 Dec', '04 Dec', '05 Dec', '05 Dec', '06 Dec', '06 Dec'];

The real arrays are much longer, circa 1,000 values with corresponding dates spanning 10 days. I am trying to get the average value for each date to make it much easier to display using apexcharts.

What I am trying to get to is something like this:

values = [100,93.75,87.5,65];
dates = ['03 Dec', '04 Dec', '05 Dec', '06 Dec'];

or indeed:

{03 Dec: '100', 04 Dec: '93.75', 05 Dec: '87.5', 06 Dec: '65'}

I've tried to combine with dates.reduce but I'm stuck with how to average the values for each day.

Any pointers would be gratefully received. Thank you.

CodePudding user response:

Try the following code. It results in an object with the dates as properties and the averages as corresponding values:

var values = [100,100,95,80,100,100,87,88,90,40];
var dates = ['03 Dec', '03 Dec', '04 Dec', '04 Dec', '04 Dec', '04 Dec', '05 Dec', '05 Dec', '06 Dec', '06 Dec'];
var averages={};
var lastdate="",total,count;
dates.forEach( (currentValue, index, )=>{
    if (currentValue !== lastdate) {
        if (lastdate !== "") {
            averages[lastdate] = total/count;
        }
        lastdate=currentValue;
        total=0;
        count=0;
    }
    total  = values[index];
    count  ;
})
averages[lastdate] = total/count;
console.log(averages);

CodePudding user response:

This should work. See comments in code for explanation, ended up making more sense that way.

const values = [100,100,95,80,100,100,87,88,90,40];
const dates = ['03 Dec', '03 Dec', '04 Dec', '04 Dec', '04 Dec', '04 Dec', '05 Dec', '05 Dec', '06 Dec', '06 Dec'];

const result = {};

for (let i = 0; i < dates.length; i  ) {
  const date = dates[i];

  if (!result[date]) {
    // create a property in the object with the current date and set it to the sum of the values that match the current date
    result[date] = values.filter((value, index) => dates[index] === date).reduce((total, value) => total   value, 0);
  }
}

for (const date in result) {
  // Divide the sum of values for the current date by the number of values that match the current date
  result[date] /= values.filter((value, index) => dates[index] === date).length;
}

console.log(result);

  • Related