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

How to sum an array of objects with a condition in typescript

Hi I am doing addition of key value from objects of an array. I want to exclude the object from the addition if it has some conditions. Example:

var arrItem = [{"id": 1, "value":100},{"id": 2, "value":300},{"id": 3, "value":400}];

//addition
this.sum = arrItem.map((a:any) => a.value).reduce(function (a:any, b:any) {
          return a + b;
        });

console.log(this.sum) // ====>>> getting 800

I want to exclude object with id==2 from summation. How I can filter this out so that I will get result as ==> 500

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

>Solution :

You can do it with reduce:

this.sum = arrItem.reduce((acc, val) => {
  if (val.id !== 2) return acc + val.value;
  return acc;
}, 0);
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