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.
CodePudding user response:
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
CodePudding user response:
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);
