Skip to content
Advertisement

how to alter reduce function so it produce different result

I have this array:

JavaScript

I want to transform that array into

JavaScript

I have this code that doing about that:

JavaScript

What it missing is ignoring the sections. Any ideas how to modify that reduce function so it will produce expected result?

To determine a section I came up with this funciton:

JavaScript

Advertisement

Answer

I would use the same approach from my answer to another (formerly asked) question of the OP … “Transform array in to object with custom properties” … and adapt it according to the OP’s new requirements.

Thus one would stay with the reduce based approach which does not depend on outer scope references for keeping track of the currently to be built/aggregated property but instead makes this information part of the reducer function’s first parameter, the previousValue which serves as an accumulator/collector object.

As for the OP’s task, this collector would feature 2 properties, the sectionKey and the result, where the former holds the state of the currently processed property name, and the latter being the programmatically built result-array of section-items.

JavaScript
JavaScript
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement