问题
I have a deeply nested javascript object with an unlimited amout of children. Every child has a value.
var object = {
value: 1,
children: {
value: 10,
children:{
value: 2,
children: {...}
}
}
}
All attempts to make a recursive function did not succeed, it turned out to go down only to a lower level.
回答1:
After flattening your linked list into an array, you can use Array.prototype.reduce() with an accumulator that is a tuple of min
and max
, starting with initial values of Infinity
and -Infinity
respectively to match the implementations of Math.min() and Math.max():
const object = {
value: 1,
children: {
value: 10,
children: {
value: 2,
children: {
value: 5,
children: null
}
}
}
}
const flat = o => o == null || o.value == null ? [] : [o.value, ...flat(o.children)]
const [min, max] = flat(object).reduce(
([min, max], value) => [Math.min(min, value), Math.max(max, value)],
[Infinity, -Infinity]
)
console.log(min, max)
回答2:
Since children
is an object with only one value (vs an array with potentially many), this is a pretty simple recursive function. The base case is when there are no children in which case both min and max are just the value. Otherwise recurse on the children to find the min and max:
var object = {
value: -10,
children: {
value: 4,
children:{
value: 200,
children: {
value: -100,
children: null
}
}
}
}
function getMinMax(obj) {
if (!obj.children || obj.children.value == undefined)
return {min: obj.value, max: obj.value}
else {
let m = getMinMax(obj.children)
return {min: Math.min(obj.value, m.min), max: Math.max(obj.value, m.max)}
}
}
console.log(getMinMax(object))
回答3:
Short and simple, for min change Math.max
to Math.min
var test = {
value: 1,
children: {
value: 10,
children:{
value: 2,
children: {}
}
}
}
function findMaxValue(obj) {
if (Object.keys(obj.children).length === 0) {
return obj.value;
}
return Math.max(obj.value, findMaxValue(obj.children))
}
console.log(findMaxValue(test))
来源:https://stackoverflow.com/questions/53379069/find-the-minimum-and-maximum-values-in-the-nested-object