我有一个深度嵌套的 javascript 对象,其子对象的数量不受限制。每个 child 都有其值(value)。
var object = {
value: 1,
children: {
value: 10,
children:{
value: 2,
children: {...}
}
}
}
所有创建递归函数的尝试都没有成功,结果只是下降到较低的级别。
最佳答案
将链表展平为数组后,您可以使用 Array.prototype.reduce()
累加器是 min
和 max
的元组,分别从 Infinity
和 -Infinity
的初始值开始匹配 Math.min()
的实现和 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)
关于javascript - 查找嵌套对象中的最小值和最大值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53379069/