Page 101 - JavaScript
P. 101
array.reduce((obj, current) => Object.assign(obj, {
[current.key]: current.value
}), {});
7
array.reduce((obj, current) => ({...obj, [current.key]: current.value}), {});
Note that the Rest/Spread Properties is not in the list of finished proposals of ES2016. It isn't
supported by ES2016. But we can use babel plugin babel-plugin-transform-object-rest-spread to
support it.
All of the above examples for Flatten Array result in:
{
one: 1,
two: 2,
three: 3
}
5.1
Map Using Reduce
As another example of using the initial value parameter, consider the task of calling a function on
an array of items, returning the results in a new array. Since arrays are ordinary values and list
concatenation is an ordinary function, we can use reduce to accumulate a list, as the following
example demonstrates:
function map(list, fn) {
return list.reduce(function(newList, item) {
return newList.concat(fn(item));
}, []);
}
// Usage:
map([1, 2, 3], function(n) { return n * n; });
// → [1, 4, 9]
Note that this is for illustration (of the initial value parameter) only, use the native map for working
with list transformations (see Mapping values for the details).
5.1
Find Min or Max Value
We can use the accumulator to keep track of an array element as well. Here is an example
leveraging this to find the min value:
https://riptutorial.com/ 58

