简体   繁体   English

根据字典数组中的公共键查找比率

[英]Find Ratio based on common keys in array of dictionaries

Need to write a function that calculates the ratio based on the common value of keys.需要写一个function,根据key的共同值计算比例。 Would like to control the key which are eligble to be considered for finding the ratio.想要控制有资格被考虑用于查找比率的密钥。

num = [{"HCOName":8919,"timestamp":"2019-01-01T00:00:00.000Z","Territory":"USA"},
       {"HCOName":8275,"timestamp":"2019-02-01T00:00:00.000Z","Territory":"USA"}, 
       {"HCOName":8107,"timestamp":"2019-03-01T00:00:00.000Z","Territory":"USA"}, 
       {"HCOName":8255,"timestamp":"2019-04-01T00:00:00.000Z","Territory":"BRAZIL"}, 
       {"HCOName":8802,"timestamp":"2019-05-01T00:00:00.000Z","Territory":"BRAZIL"}];
den = [{"HCP":9,"timestamp":"2019-01-01T00:00:00.000Z","Territory":"USA"},
       {"HCP":5,"timestamp":"2019-02-01T00:00:00.000Z","Territory":"USA"},
       {"HCP":7,"timestamp":"2019-03-01T00:00:00.000Z","Territory":"USA"},
       {"HCP":2,"timestamp":"2019-05-01T00:00:00.000Z","Territory":"CANADA"}];

commonDimesion= ["timestamp", "Territory"]
function ratio(num,den,commonDimesion){
   <some code>
} 

expected result:预期结果:

    [{"ratioResult":991,"timestamp":"2019-01-01T00:00:00.000Z","Territory":"USA"},
    {"ratioResult":1655,"timestamp":"2019-02-01T00:00:00.000Z","Territory":"USA"}, 
    {"ratioResult":1158.14,"timestamp":"2019-03-01T00:00:00.000Z","Territory":"USA"}]

You can make use of reduce function. Like this:您可以使用reduce function。像这样:

 var num = [{"HCOName":8919,"timestamp":"2019-01-01T00:00:00.000Z","Territory":"USA"}, {"HCOName":8275,"timestamp":"2019-02-01T00:00:00.000Z","Territory":"USA"}, {"HCOName":8107,"timestamp":"2019-03-01T00:00:00.000Z","Territory":"USA"}, {"HCOName":8255,"timestamp":"2019-04-01T00:00:00.000Z","Territory":"BRAZIL"}, {"HCOName":8802,"timestamp":"2019-05-01T00:00:00.000Z","Territory":"BRAZIL"}]; var den = [{"HCP":9,"timestamp":"2019-01-01T00:00:00.000Z","Territory":"USA"}, {"HCP":5,"timestamp":"2019-02-01T00:00:00.000Z","Territory":"USA"}, {"HCP":7,"timestamp":"2019-03-01T00:00:00.000Z","Territory":"USA"}, {"HCP":2,"timestamp":"2019-05-01T00:00:00.000Z","Territory":"CANADA"}]; var commonDimesion= ["timestamp", "Territory"]; var result = num.reduce((acc, {HCOName, ...rest})=>{ denValue = den.filter(val=>commonDimesion.every(k=>val[k]==rest[k]))[0]; if(denValue) acc.push({rationResult:HCOName/ denValue.HCP, ...rest}); return acc; },[]); console.log(result);

Now, you can integrate this code in your function and return the result .现在,您可以将此代码集成到您的 function 中并返回result I hope this helps.我希望这有帮助。 Thanks!谢谢!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM