0
Follow
5
View

Add total values in dictionary by reduce function in javascript

duanyu11111 注册会员
2023-01-26 07:33

The reduce function works like so:

reduce((previousValue, currentValue) => { /* ... */ } )

so what you need to do is:

const test = scores.reduce((acc, item) =>acc + item.score, 0)

Please read the documentation MDN is a really good website for this: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce

dlzthzzh 注册会员
2023-01-26 07:33

fistful you should pass previousValue, currentValue arguments instead of item, second_item. I really suggest you to read documentation

Your code is not returning the total score because reduce you're trying to sum number and undefined (Do console.log() inside of the reduce you will understand more).

You can make something like that;

  const scores = [
    {
      team: "A",
      score: 20,
    },
    {
      team: "B",
      score: 17,
    },
    {
      team: "C",
      score: 23,
    },
    {
      team: "D",
      score: 13,
    },
  ];

  const totalScore = scores.reduce(function (a, b) {
    return { score: a.score + b.score }; // returns object with property x
  });

  console.log(totalScore.score);

About the Author

Question Info

Publish Time
2023-01-26 07:33
Update Time
2023-01-26 07:33

Related Question

Skywalking

c# Nhibernate linq在IQueryable Oracle Clob xml字符串列中的特殊字符

Linux下Apache的安装与配置 主机ip可以建立连接 可是两个虚拟ip都是连接失败

IntelliJ传递上面类注释的完全导入路径

如何在docker-compose上禁用MySQL binlog

Linux操作系统mv命令疑问

如何改变docker映像构建与spring-boot-maven-plugin env从POSIX到C.UTF-8开箱即用

关于hydra爆破linux密码的问题

v-model: searchInfo is not defined

MongoDB查找和unwind