admin管理员组文章数量:1425921
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
-
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
1 Answer
Reset to default 6You can do it with reduce:
this.sum = arrItem.reduce((acc, val) => {
if (val.id !== 2) return acc + val.value;
return acc;
}, 0);
本文标签: javascriptHow to sum an array of objects with a condition in typescriptStack Overflow
版权声明:本文标题:javascript - How to sum an array of objects with a condition in typescript - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745456438a2659123.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论