1

I have a question regarding underscore's reduce behaviour with an object.

Given the following object:

var data = [ { type: "A", val: 2 },
             { type: "B", val: 3 },
             { type: "R", val: 3 },
             { type: "L", val: 3 },
             { type: "R", val: 3 },
             { type: "A", val: 1 },
             { type: "B", val: 5 } ];

And the following function:

output = _(data).reduce(function(mem, d) {

                console.log(mem);
                mem[d.type] = d.type;

                return mem
         }, {});

The output in the console for all 8 iterations is:

 Object { A: "A", B: "B", R: "R", L: "L" }

1) Why is this happening, shouldn't the first output not be empty as I've given it a {} as my initial state?

2) Why is it the case that all the unique types appear to have been found from the first iteration?

Any help would be appreciated, thanks.

clery00
  • 251
  • 2
  • 14
  • You're logging the object and then changing it on the next iteration; this is an issue of the way objects are logged in the browser, not the way `reduce` works. – Evan Davis Sep 02 '14 at 20:40
  • you're not actually using _.reduce, you're using [].reduce... – dandavis Sep 02 '14 at 20:41
  • @dandavis regardless of what `_` is, that is not related to the issue at hand. – 000 Sep 02 '14 at 20:44
  • i like titles to reflect the code. besides, it's what reduce() is that doesn't matter ;) – dandavis Sep 02 '14 at 20:49
  • I really don't like the Marked As Duplicate text `"This question has been asked before and already has an answer."`. Sure the questions have similar answers, but the question has not been asked before. – 000 Sep 02 '14 at 21:28

1 Answers1

1

There is no problem with your code.

The problem is that your console does not automatically expand objects until you click the little triangle to expand that object. It shows you a truncated reference to the object, which does not become real until you expand the object.

To see this, check out this series of screenshots:

I set up the object: http://i.imgur.com/nTU3Ld0.png

Then I expand the console from the first output: http://i.imgur.com/NCCpgfd.png

000
  • 26,951
  • 10
  • 71
  • 101
  • Wow, I checked Chrome and Firefox before posting. Looked at it in firebug and lo and behold it's giving the expected behaviour. Thanks for the help. – clery00 Sep 02 '14 at 20:54