[英]How to interpolate json string in javascript
我正在使用plotly創建圖表,其數據為json字符串格式。 這是數據
var data = [
{
"name ": "abc",
"id ": 1,
"sales": 205
},
{
"name ": "abc",
"id ": 1,
"sales": 300
},
{
"name ": "abc",
"id ": 1,
"sales": -1
},
{
"name ": "abc",
"id ": 1,
"sales": -1
},
{
"name ": "abc",
"id ": 1,
"sales": 800
},
{
"name ": "abc",
"id ": 1,
"sales": 450
},
{
"name ": "pqr",
"id ": 2,
"sales": 214
},
{
"name ": "pqr",
"id ": 2,
"sales": 560
},
{
"name ": "pqr",
"id ": 2,
"sales": 490
},
{
"name ": "pqr",
"id ": 2,
"sales": -1
},
{
"name ": "pqr",
"id ": 2,
"sales": 650
}]
我在-1
表示的數據的銷售欄中缺少一些值。 我正在嘗試通過計算復合年增長率( CAGR )來對那些缺失的數據進行插值。 所以我決定先指數-1
說firstidx
相同的內id
和最后一個索引-1
說lastidx
相同的內id
和計算CAGR為每鏈路提到的公式,並填寫代替那些數據-1
這不過是缺失值。 我嘗試使用javascript中的一些虛擬代碼,但無法通過。
CAGR的公式為:
CAGR =(EV / BV)1 / n-1
哪里:
EV =投資的期末值BV =投資的期初值n =期間數(月,年等)
偽碼
function interpolate(jsString){
var firstidx = data.FirstIndexOf(data[sales]) - number(1) // subtracted 1 because to get the value for beginning value to calculate CAGR
var lastidx = data.lastIndexOf(data[sales]) + number(1) // added 1 because to get the value for ending value to calculate CAGR
var n = lastidx - (data.IndexOf(data[sales])
var cagr = ((lastidx/firstidx)^(1/n)-1) //formula of CAGR
}
關於如何實現該功能的任何建議。
謝謝
多姆尼克
只需find
索引名稱相等,然后取其值即可:
function fillSales(product, i, products) {
// If sales already exists, stop here:
if(product.sales !== -1) return;
const BVi = products.findIndex(p => p.name === product.name);
const BV = (products[BVi] || {}).sales || 0;
const EVi = products.reduceRight((res, p, i) => res ? res : p.name === product.name ? i : null, null);
const EV = (products[EVi] || {}).sales || 0;
product.sales = (EV / BV) ** (1/ (EVi - BVi));
}
所以可以做到:
data.forEach(fillSales);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.