Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

237
Views
Add total values in dictionary by reduce function in javascript

I am learning the reduce function and it's capabilities however I cannot seem to figure out how to use it with dictionaries.

For example, I have the following dictionary:

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

I want to add all the values score in the neatest way possible, I have tried approaching this myself with:

const test = scores.reduce((first_item, second_item) =>{
  console.log(first_item.score, second_item.score)
    return first_item.score + second_item.score
  }
)

However, it doesn't add up the values, and it seems to only work for the first two values in the dict. What's an easier alternative that would work for larger dictionaries on a smaller line of code? as I see it, I would have to keep including variables in the reduce function to match the number of keys.

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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

about 4 years ago · Juan Pablo Isaza Report

0

fistful you should pass previousValue, currentValue arguments instead of first_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 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!