如何对JavaScript数组对象形式的特定搜索ID中的值求和? [英] How to sum value in javascript array object form specific search id?

查看:46
本文介绍了如何对JavaScript数组对象形式的特定搜索ID中的值求和?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有如下所示的javascript数组对象.我需要基于数组对象中的seach id求和.

I have javascript array object as below. My need is to sum value base on seach id in the array object.

var array = [
{ id: 1, val: 10 }, 
{ id: 2, val: 25 }, 
{ id: 3, val: 20 }, 
{ id: 1, val: 30 }, 
{ id: 1, val: 25 }, 
{ id: 2, val: 10 }, 
{ id: 1, val: 20 }
],

例如,id 1的值总和为10 + 30 + 25 + 20 = 85,这可能是链接linq所致,但是我不确定在javascript中.感谢您提供所有答案.

For example sum of value for id 1 is 10 + 30 + 25 + 20 = 85 , It may be something link linq but I'm not sure in javascript. Thanks for all answers.

推荐答案

您可以结合使用filter和reduce来获得所需的结果:

You can use a combination of filter and reduce to get the result you want:

sumOfId = (id) => array.filter(i => i.id === id).reduce((a, b) => a + b.val, 0);

用法:

const sumOf1 = sumOfId(1); //85

阅读材料:

Array.prototype.filter

Array.prototype.reduce

这篇关于如何对JavaScript数组对象形式的特定搜索ID中的值求和?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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