简体   繁体   中英

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

 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 . I hope this helps. Thanks!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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