Home > Software design >  Calculate Percentage of each key in Object
Calculate Percentage of each key in Object

Time:10-03

So I have this data, how can I compute their respective percentages?

  const items = {
       google: 76,
       apple: 66,
       netflix: 53
  }  

Thank you

CodePudding user response:

A simple reference for you by using reduce()

const items = {
       google: 76,
       apple: 66,
       netflix: 53
  }
 
let total = Object.values(items).reduce((acc,val) =>{
  acc  = val
  return acc;
},0)

let result = Object.keys(items).reduce((acc,key) => {
  let val = items[key]
  //acc[key] = val
  acc[key] = (val/total*100).toFixed(2)  "%"   " : "   val
  return acc
},{})

console.log(result)

  • Related