In the example code in the question there is no return , hence this function does not output anything, but it already runs through all the elements in the graph.
The first thing to change is to add return , which will return the desired value.
What is needed in this case is a maximum of several numbers: the value of the value field, and the values ββfrom the children field.
By applying the deepMap function to each element of the children array, you can have a list of maximum values ββat each level.
To find the maximum number of several, you can use the function Math.max , as well as the spread operator , which allows you to conveniently transfer an array to it.
Since the children field may be missing, you need to add the appropriate check and in the case of its execution immediately return value .
Having accepted all the notes, the function can be changed as follows:
const deepMap = (obj) => { if (!obj.children) return obj.value; // Π΅ΡΠ»ΠΈ Π½Π΅Ρ Π΄Π΅ΡΠ΅ΠΉ - ΡΡΠ°Π·Ρ Π²Π΅ΡΠ½ΡΡΡ value var maxChildren = obj.children.map(deepMap); // ΠΏΠΎΠ»ΡΡΠ°Π΅ΠΌ ΠΌΠ°ΠΊΡΠΈΠΌΠ°Π»ΡΠ½ΡΡ
ΠΈΠ· Π΄Π΅ΡΠ΅ΠΉ return Math.max(obj.value, ...maxChildren); // Π²ΠΎΠ·Π²ΡΠ°ΡΠ°Π΅ΠΌ ΠΌΠ°ΠΊΡΠΈΠΌΠ°Π»ΡΠ½ΠΎΠ΅ ΠΈΠ· Π·Π½Π°ΡΠ΅Π½ΠΈΠΉ. };
If you remove local variables and if you can get the following option:
function deepMax(obj){ return Math.max(obj.value, ...(obj.children||[]).map(deepMax)); }
Example:
const deepMap = (obj) => { if (!obj.children) return obj.value; // Π΅ΡΠ»ΠΈ Π½Π΅Ρ Π΄Π΅ΡΠ΅ΠΉ - ΡΡΠ°Π·Ρ Π²Π΅ΡΠ½ΡΡΡ value var maxChildren = obj.children.map(deepMap); // ΠΏΠΎΠ»ΡΡΠ°Π΅ΠΌ ΠΌΠ°ΠΊΡΠΈΠΌΠ°Π»ΡΠ½ΡΡ
ΠΈΠ· Π΄Π΅ΡΠ΅ΠΉ return Math.max(obj.value, ...maxChildren); // Π²ΠΎΠ·Π²ΡΠ°ΡΠ°Π΅ΠΌ ΠΌΠ°ΠΊΡΠΈΠΌΠ°Π»ΡΠ½ΠΎΠ΅ ΠΈΠ· Π·Π½Π°ΡΠ΅Π½ΠΈΠΉ. }; var graph = { value: 75, children: [{ value: 18, children: [{ value: 35, children: [{ value: 35, children: [{ value: 66, children: [{ value: 29, children: [{ value: 85 }] }] }] }] }] }] } console.log(deepMap(graph));