Very often, we have to transform objects from one shape to another. My favorite tool for such transformations is the
reduce function. Let's say that we have the following array of objects:
And we need the total number of years for each of the languages. The solution involves looping over the items and some value aggregation. Precisely what
reduce is made for:
reduce is a method of the Array prototype. It allows us to accumulate a value by looping over the array's items.
It is possible to use the function on objects too. Not directly, but we can pass the object to
Object.keys. We will get back an array of all the properties, and we can iterate over them. Let's continue the example and ask another question - how many years in total?