I am attempting to utilize the reduce method to generate an object that displays the percentage of occurrence of different countries in a given list.
Input:
countriesList = ["US","US","US","UK","IT","IT"]
Desired Output:
percCountriesList = [{"country": "US", "weight": 0.5}, {"country": "UK", "weight": 0.1666}, {"country": "IT", "weight": 0.3333}]
Method for calculating percentages:
const countriesList = ["US","US","US","UK","IT","IT"]
const weightPercCountries = countriesList.reduce((pcts, x) => {
pcts[x] = (pcts, (pcts[x] ? pcts[x] : 0) + 100 / countriesList.length);
return pcts;
}, []);
console.log(weightPercCountries)
Having obtained the list of percentages:
[50, 16.666666666666668, 33.33333333...]
Now, how can I format the desired output (country + weight) in JSON format? Appreciate any help!