Skip to content
Advertisement

Calculate Percentage of each key in Object

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

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

Thank you

Advertisement

Answer

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)
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement