Hello In javascript I have one array object
var arr=[{param: 'Invalid Entity Name', total: 2},
{param: 'Missing File', total: 1}];
console.log(arr);
My want is add one more attribute to objects. And this will be percentage. I can do it with two for loop as worst case but I want easier and smarter solution. as final result I want
var arr=[{param: 'Invalid Entity Name', total: 2,percent:67},
{param: 'Missing File', total: 1,percent:33}];
console.log(arr);
How can I make it?
Thanks in advance
>Solution :
In your case you have 2 things to do.
The first one is calculating the total and the second is for each element to calculate the percentage.
As you mention, you have to do 2 for loops indidually because each element have to know the total to calculate it’s percentage
This can be done with the reduce and forEach methods.
var arr=[
{param: 'Invalid Entity Name', total: 2},
{param: 'Missing File', total: 1}
];
const sumTotal = arr.reduce((total, current) => total + current.total, 0)
arr.forEach(element => {
element.percent = Math.round(element.total / sumTotal * 100)
})
console.log(arr)