javascript - How to sum an array of objects with a condition in typescript - Stack Overflow

Hi I am doing addition of key value from objects of an array. I want to exclude the object from the add

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

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

Share Improve this question asked Apr 12, 2022 at 6:37 Optimist RohitOptimist Rohit 42814 silver badges26 bronze badges 2
  • arrItem.filter() ? – Tobias S. Commented Apr 12, 2022 at 6:39
  • @TobiasS. I am not getting exactly how to use filter() here. – Optimist Rohit Commented Apr 12, 2022 at 6:41
Add a ment  | 

1 Answer 1

Reset to default 6

You can do it with reduce:

this.sum = arrItem.reduce((acc, val) => {
  if (val.id !== 2) return acc + val.value;
  return acc;
}, 0);

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745456438a4628507.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信