10

I have an object called student, with two properties, name and score. I am trying to perform calculations using the score property but am having trouble accessing the property from the array of students. Currently, I'm trying to get the sum of the scores with the following code:

var sum = students.reduce(function(a, b) { 
                    return {sum: a.score + b.score}
                    })

This returns an undefined value and causes display weirdness in firefox. I can't seem to find the error.

Is there no way to just access parameters simply, (i.e. var myVar = myArray. myObject.myProperty;)?

1
  • 2
    The second time your callback is invoked, a will be the object previously returned, and that object has no score property. (Some console.log() statements in your callback should show you the problem...)
    – nnnnnn
    Mar 14, 2016 at 3:00

3 Answers 3

20

I think you have a misunderstanding about how reduce works. For each element in the array, it executes the provided function. The first argument is an "accumulator"; something that's passed along as each element is visited (actually, it's the return value of the function from the last element, but it's usually used as an accumulator). The second argument is the element being visited. So what I think you want is this:

var sum = students.reduce(function(a, s) {
    a.sum += s.score;
    return a;
}, { sum: 0 });

When you invoke reduce, you can provide the initial value of the accumulator (otherwise it takes on the value of the first element, and the visitation starts with the second element). Here, we provide an object with a sum property set to zero.

If all you want is the sum (not an object with a sum property), it can be even simpler:

var sum = students.reduce(function(a, s) {
    return a += s.score;
}, 0);
5
  • 1
    Just making sure I understand the syntax correctly, in your second example. a is an accumulator? You said it was a return value but if they're both defined seperately aren't they different things? Either way, a holds the current value. s is the array element, in this case, each student object, so s.score is student.score. I'm not sure what += is, but that one will be obvious enough once I've looked it up, not had to use it until now. }, 0); what is the zero for? If it's an inital value for var sum, why do we need it, wouldn't the uninitialised default value work? Mar 14, 2016 at 3:33
  • 2
    @SpaceOstrich the first argument is an accumulator, whether that's a running total, or a current max/min, or an object you're appending things to, or an array, it accumulates the returns of operations you're running, and is equal to the previous return value. As for "Why the 0", if reduce is given no default, and there is more than 1 element in the array, then the first run through reduce uses arr[0] as a and arr[1] as b. In your case, before you transform it with map you could see how that would cause you problems requiring you to check if a was one shape or another.
    – Norguard
    Mar 14, 2016 at 3:48
  • 1
    I like to call the 'accumulator' with the same name of my variable. It helps understanding what's going on. An example using ESNext: let sum = students.reduce((sum, student) => { ... }, init); Mar 14, 2016 at 3:56
  • 1
    I like that approach, @rafaelbiten, and I often use it when my accumulator is something simple like sum or max or whatever. But sometimes it's a complex thing: like an object in which I'm storing lots of different characteristics of the array elements. And then a or accumulator works just as well as anything. Mar 14, 2016 at 3:58
  • 1
    This is one of the best explanations of reduce I've read. Thank you! May 26, 2019 at 11:56
4

To add to Ethan's sufficient explanation of reduce you might also consider a map into the appropriate format for reduction into a single value.

students.map( student => student.score ).reduce( (a, b) => a + b, 0 );
2

There is nothing wrong with your code that a little debugging could not help with. Place a breakpoint on the return statement. When the engine stops there, examine the values of a and b. Alternatively, as a commenter suggested, you could add a console.log line there, to output the values to the console. In either case, you will see that they are the first two values in the array--this is how reduce behaves if you fail to give it the second parameter. The returned value will be {sum: students[0].score + students[1].score}. Now continue execution. You will break again at the return statement; examine a and b again. You will see that a is not a student, nor a number, but rather the {sum: } object you returned on the previous iteration, which has no score property. Assuming the sum of the first two scores was 192, the next return value will thus be {sum: {sum: 192}.score + students[2].score}. That turns into {sum: undefined + students[2].score}, which in turn becomes NaN, since adding anything to undefined returns NaN. Things now go downhill from there.

When you discover that the second time through the loop, a is {sum: 192}, you should realize that that is neither a student whose score you can take, nor a value you can add something to. With a little additional reading of the reduce documentation, and perhaps looking at a few examples, you should be able to figure out that you need to return the sum itself, not an object containing a property sum. That sum will then become the a in the next iteration of the loop. To make this work, you'll need to give reduce an initial value of 0 as its second parameter.

As you move ahead on your programming journey, you'll run into many such bumps in the road. Unfortunately, you cannot depend on SO people to solve all of them for you, and even if they do, you could remain stuck for hours or days until they answer. You really need to learn how to pin down and solve such problems for yourself. The debugger is key to doing that, so there is no alternative to learning how to bring it up, set breakpoints, and examine variables. Take a few hours out of your schedule and read through the docs carefully. You can find them at https://developers.google.com/web/tools/chrome-devtools/. Here is a good overview how to debug small programs; http://ericlippert.com/2014/03/05/how-to-debug-small-programs/.

2
  • Thanks for the link, debugging is something I've not had much experience with beyond adding console print lines to figure out which exact part of a program is being reached before it breaks. If breakpoints do what they sound like they do that sounds like an invaluable tool, I'd just been lamenting the fact that I can't check the value of variables and the like in real time. Mar 15, 2016 at 1:45
  • You can also put a debugger; statement in your program to put yourself into the debugger.
    – user663031
    Mar 15, 2016 at 3:28

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.