具有特定属性的数组的元素总和 [英] Sum elements of an array with specific attribute

查看:29
本文介绍了具有特定属性的数组的元素总和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想总结一个数组的元素,但不是全部。假设我的数组是:

I wanna sum the elements of an array, but not all. Let's say that my array is:

var example = [
                   {"id": 1, "value": 50, "active": true}, 
                   {"id": 2, "value": 70, "active": false}, 
                   {"id": 3, "value": 45, "active": true}, 
                   {"id": 4, "value": 50, "active": false}
               ];

我需要做的就是将个值相加具有 active:true 的元素。

What I need to do is sum just the values of the elements with "active":true.

有办法吗?也许太简单了,但是现在,我的大脑已经死了。

There's a way to do that? Maybe is too simple, but right now, my brain is dead.

我正在使用Javascript和AngularJs。

I'm using Javascript and AngularJs.

预先感谢。

推荐答案

您可以使用过滤器减少像这样:

var a = [{"id": 1, "value": 50, "active": true}, {"id": 2, "value": 70, "active": false}, {"id": 3, "value": 45, "active": true}, {"id": 4, "value": 50, "active": false}]

var result = a.filter(o => o.active).reduce((acc, cur) => cur.value + acc, 0)

console.log(result)

这篇关于具有特定属性的数组的元素总和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆