0

I want to change the percentage attribute for each object I tried using Array.map() to loop through each object and use a setState(prevState => {return {...prevState, percentage: newValue}}) inside the Array.map(), But clearly this is incorrect and I don't know how to change the value of this attribute for each object

This is the Array of objects

interface Data {
  state: string;
  value: number;
  percentage: number;
}

const [data, setData] = useState<Data[]>([
{
  state: 'SP',
  value: 67836.66,
  percentage: 0
},
{
  state: 'RJ',
  value: 36678.66,
  percentage: 0
},
{
  state: 'MG',
  value: 29229.88,
  percentage: 0
},
{
  state: 'ES',
  value: 27165.48,
  percentage: 0
},
{
  state: 'Outros',
  value: 19849.53,
  percentage: 0
},

])
2
  • Do you want them all to be the same percentage? What are you doing to calculate the percentage for each item? Commented Jul 3, 2022 at 20:04
  • @JoelHager each object has a different percentage let tot = 0 data.map(item => tot += item.value) data.map(item => (item.value * 100) / tot) will be something like this Commented Jul 3, 2022 at 20:43

1 Answer 1

1

You have to reduce first to get the total, and then apply the calculation in another loop.

Resource on reducers (to accumulate a total through an array) https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce

const list = [
  {
    state: 'SP',
    value: 67836.66,
    percentage: 0
  },
  {
    state: 'RJ',
    value: 36678.66,
    percentage: 0
  },
  {
    state: 'MG',
    value: 29229.88,
    percentage: 0
  },
  {
    state: 'ES',
    value: 27165.48,
    percentage: 0
  },
  {
    state: 'Outros',
    value: 19849.53,
    percentage: 0
  },
]

// Where we compute the total
let total = list.reduce((acc, item) => {
  // console.log(acc, item)
  return acc += item.value
}, 0)

// Where we apply the percentages (note: map also works)
list.forEach((item) => item.percentage = ((item.value / total) * 100).toFixed(2))

// If you add them up, you get 100 (percent)
console.log(list)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.