DEV Community

Discussion on: How to use the `reduce` Method in JavaScript (and React)

Collapse
 
yogesnsamy profile image
yogesnsamy

Thank you for your feedback. Quoting MDN, the documentation does say it returns a single value.

The reduce() method executes a reducer function (that you provide) on each element of the array, resulting in a single output value.

I'm pretty new to the method, may I know more about your last reference to thisArg please?

Collapse
 
timhlm profile image
moth • Edited

Single value doesn't mean it can't be a collection type I think is the OP's point. For example you can use reduce to easily make a lookup map out of an array:

[
  { id: 123, name: "Ben" },
  { id: 456, name: "Sarah" },
  { id: 789, name: "Jane" }
].reduce((acc, e) => {
  return {
    [e.id]: e.name,
    ...acc
  }
}, {})

/*
output-
{
  123: Ben,
  456: Sarah,
  789: Jane
}
*/
Enter fullscreen mode Exit fullscreen mode
Thread Thread
 
yogesnsamy profile image
yogesnsamy

Yes, thank you for a nice example.