Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Javasctipt better solution to add one property to array objects

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading