# calculate average and percentages in javascript

1

How I need a little help, I have the following arrangement:

And what I need is to transform `quantity` in%, corresponding to the total average of all the amounts, that is:

the total sum of `quantity` is 791 which is equivalent to 100%

then 656 would correspond to 83%, 31 would correspond to 4% and so on until we have all the% in the same arrangement,

``````- Sumar todo para obtener cada %
- Multiplicar el numero x 100 y divido por la suma total
``````

How would you apply it with the smallest possible code in javascript?

I have the following code, but it does not give me what I want.

``````totalLocation = 0;

firstsix.forEach(element => {
totalLocation = totalLocation + element.quantity;
console.log(element.quantity * 100 / totalLocation)

})
``````

asked by Hernan Humaña 24.07.2018 в 20:24
source

2

It will not work, because the process you want to perform must be separated into two well-defined steps, you must first calculate the total amount of% co_of% of objects you have.

To later take your approximation in% according to that total. It does not work now because `array` only in the last iteration will have the correct total, in the previous iterations no.

``````var firstsix = [{quantity :656},{quantity :31},{quantity :28},{quantity :28},{quantity :25},{quantity :23}];
var totalLocation = 0;
firstsix.forEach(element => {
totalLocation += element.quantity;
})
firstsix.forEach(element => {
console.log(element.quantity * 100 / totalLocation)
})
// O en un sola línea
//firstsix.forEach(element => totalLocation += element.quantity);
//firstsix.forEach(element => console.log(element.quantity * 100 / totalLocation));``````