查找嵌套对象中的最小值和最大值 [英] Find the minimum and maximum values in the nested object

查看:64
本文介绍了查找嵌套对象中的最小值和最大值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个深度嵌套的 javascript 对象,其中包含无限数量的孩子.每个孩子都有自己的价值.

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.

推荐答案

将你的链表扁平化成数组后,你可以使用 Array.prototype.reduce() 带有一个 min<元组的累加器/code> 和 max,分别从 Infinity-Infinity 的初始值开始,以匹配 Math.min()Math.max():

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)

这篇关于查找嵌套对象中的最小值和最大值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆