2017-10-20 50 views
0

我有兩個相互關聯的數組。 Array A保存每週日期和Array B保存每週價格。每個星期五新數據都會通過API發佈並推送到這些數組中,因此有些月份有5個元素(即Jan),而有些月份只有4個元素(即2月份)。看下面的例子。使用Javascript和/或jQuery將每週數據轉換爲每月數據

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..] 

代碼:

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

我將如何能夠將它轉換爲 「月」 和 「年」 的陣列?

+1

請包括嘗試的解決方案,爲什麼他們沒有工作,和預期的結果。這真的可以幫助我們找出你的代碼的問題。謝謝! –

+0

那麼這兩個數組如何映射?數組A(月)如何映射到價格數組?使用來自API的信息創建一個json數組是否合理? –

+0

該陣列是否僅包含一年的數據? –

回答

2

您可以使用array#reduce將基於年份的數據分組,每年可以對每個月的價格進行總結。

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

+0

我認爲你增加了價格值。應該是月平均水平。 – user3062459

+0

我已經添加了價格。你想要每個月的平均價格,不是嗎? –

+0

是的請 – user3062459

相關問題