user3062459
user3062459

Reputation: 1631

Convert weekly to monthly data using Javascript and/or jQuery

I have and two array that are related to each other. Array A holds weekly dates and Array B holds weekly prices. Every Friday new data is released and pushed into these arrays via API, hence some months have 5 elements (i.e Jan) while some months have only 4 elements (i.e Feb). See example below.

Array A:

["2003-01-03", "2003-01-10", "2003-01-17", "2003-01-24", "2003-01-31", "2003-02-07", "2003-02-14", "2003-02-21", "2003-02-28", etc..]

Array B

["5.85", "5.95", "5.97", "5.91", "5.90", "5.88", "5.86", "5.84", "5.79", etc..]

Code:

var ajx = $.getJSON(api, function(data) {                 
   for (var i =0; i <= data.count -1; i++){
      $("#table").append("<tr> <td>" + data.observations[i].date + "</td> <td>" + data.observations[i].value + "</td>  </tr>");
      xaxis.push(data.observations[i].date) //Array A - weekly (default state)
      yaxis.push(data.observations[i].value) //Array B - weekly (default state)
      }

How would I be able to convert this to "monthly" AND "annual" arrays?

Upvotes: 0

Views: 681

Answers (1)

Hassan Imam
Hassan Imam

Reputation: 22534

You can use array#reduce to group data based on year and inside each year you can sum up price of each month.

const arrayA = ["2003-01-03", "2003-01-10", "2003-01-17", "2003-01-24", "2003-01-31", "2003-02-07", "2003-02-14", "2003-02-21", "2003-02-28"],
      arrayB = ["5.85", "5.95", "5.97", "5.91", "5.90", "5.88", "5.86", "5.84", "5.79"];

let result = arrayA.reduce(function(res, date, index){
  let [year, month, day] = date.split('-');
  let price = arrayB[index];
  if(year in res){
    if(month in res[year]) {
      res[year][month].price = 
          ((res[year][month].price * res[year][month].count) + +price)/(res[year][month].count+1);
      res[year][month].count += 1;
      
    } else {
      res[year][month] = {price : +price, count : 1};
    }
  } else {
    res[year] = {[month]: {price : +price, count :1}};
  }
  return res;
}, Object.create(null));

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Upvotes: 2

Related Questions