Skip to content Skip to sidebar Skip to footer

Find The Minimum And Maximum Values In The Nested Object

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, childre

Solution 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)

Solution 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))

Solution 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))

Post a Comment for "Find The Minimum And Maximum Values In The Nested Object"