-1

question:

orderData = {
'Below 500': 20,
'500-1000': 29,
'1000-1500': 30,
'1500-2000': 44,
'Above 2000': 76
}; 

Calculate the percentage of each proportion in the below format in javascript expected result:

[{
id: 1, order: "Below 500", order percentage: "10.05", restaurant: "Punjabi Tadka"
},{
id: 2, order: "500-1000", order percentage: "14.57", restaurant: "Punjabi Tadka"
},{
id: 3, order: "1000-1500", order percentage: "15.08", restaurant: "Punjabi Tadka"
},{
id: 4, order: "1500-2000", order percentage: "22.11", restaurant: "Punjabi Tadka"
},{
id: 5, order: "Above 2000", order percentage: "38.19", restaurant: "Punjabi Tadka"
}]
  • 2
    Welcome to Stack Overflow! Please take the [tour] (you get a badge!), have a look around, and read through the [help], in particular [*How do I ask a good question?*](/help/how-to-ask) I also recommend Jon Skeet's [Writing the Perfect Question](https://codeblog.jonskeet.uk/2010/08/29/writing-the-perfect-question/) and [Question Checklist](https://codeblog.jonskeet.uk/2012/11/24/stack-overflow-question-checklist/). There's no question here. What do you need to know? – T.J. Crowder Apr 24 '21 at 10:46
  • Please also take the time to look at the question preview and use the various formatting tools that are available in the Stack Overflow question editor before posting, so you can make your question clear. – T.J. Crowder Apr 24 '21 at 10:47
  • 1
    Now that Nguyễn Văn Phong has edited the question, i can see what you're asking. Your best bet here is to do your research, [search](/help/searching) for related topics on SO, and give it a go. ***If*** you get stuck and can't get unstuck after doing more research and searching, post a [mcve] of your attempt and say specifically where you're stuck. People will be glad to help. – T.J. Crowder Apr 24 '21 at 10:47
  • Create a `let sum = 0;` variable. [Loop thorough the object](https://stackoverflow.com/questions/684672/how-do-i-loop-through-or-enumerate-a-javascript-object) and calculate the sum. Loop thorough object again and create an object in each iteration and add your desired keys. Add the percentage based on the `sum` obtained earlier to each object. Push this object to an array. Here's a similar quetion: [javascript - calculate and transform object key values into percentages (on 100%)](https://stackoverflow.com/questions/27350704) – adiga Apr 24 '21 at 10:50

1 Answers1

0

orderData = {
'Below 500': 20,
'500-1000': 29,
'1000-1500': 30,
'1500-2000': 44,
'Above 2000': 76
}; 

const total = Object.values(orderData).reduce(( acc, cur ) => acc + cur, 0);
const result = Object.keys(orderData).map((key, index)=>({
  id: index + 1,
  order: key,
  order_percentage: (100 * orderData[key] / total).toFixed(2)
}))

console.log(result)
Emanuele
  • 382
  • 3
  • 9