Discover the smallest and largest values within the multi-layered object

My JavaScript object is deeply nested with an infinite number of children, each containing a value.

var object = {
     value: 1,
     children: {
      value: 10,
      children:{
       value: 2,
       children: {...}
      } 
     }
}

I've tried creating a recursive function to traverse the entire object structure, but so far it only goes down to a certain depth.

Answer №1

When your linked list is transformed into an array, you have the option to utilize Array.prototype.reduce() with an accumulator that consists of a tuple containing min and max. The process begins with initial values of Infinity for min and -Infinity for max in order to align with the functions found in 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)

Answer №2

Given that the children object only contains a single value (compared to an array with multiple values), the recursive function presented here is straightforward. The function follows a simple logic where if there are no children, then both the minimum and maximum values are equal to the sole value. On the other hand, if there are children, the function recursively navigates through them to determine the minimum and maximum values:

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

Answer №3

To make a small adjustment, simply switch from using 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.min(obj.value, findMaxValue(obj.children))
}
console.log(findMaxValue(test))

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What are the proper methods for accurately testing vuex state and mutations?

Can someone guide me on how to properly test mutations and state? I have a modal window component that is rendered when the showModal property in the state is true. There is an event triggering a mutation that changes this property. How can I verify that a ...

"Trouble with props: List items not showing up after refreshing the page

I am facing an issue with my "Event Selector" component where it is not displaying the list items as expected. The component is supposed to create a button for each item in the 'lists' passed via props. Strangely, the items do not show up upon re ...

Angular JS Visibility Toggling with Ng-Show and Ng-Hide

Working on an angular service for a login form, I've successfully implemented authentication using a factory with an http injector to handle HTTP credentials. However, I'm facing an issue in displaying an error message when incorrect credentials ...

Conditional statement in Javascript for document.cookie

I am attempting to create a basic if statement that relies on the value of a cookie. The function looks like this: function setHomePage() { if ($.cookie('settingOne') == 'jjj') { $('.secO').css('display', & ...

When state is updated, the component is re-rendered multiple times

I am working on setting the state in componentDidMount lifecycle method to verify data from local storage. Depending on whether the data exists in local storage, I either redirect the user to the login page or keep them on the dashboard. Is there a way to ...

Refresh the DATATABLE inside an AJAX call without reloading the entire page

I'm currently working with a table that utilizes the Datatable plugin. I have successfully implemented filtering and deletion functionality within the table. However, after deleting certain entries, I noticed an issue where the deleted item still app ...

"Utilizing JSON parsing in Node.js and rendering the data in a Jade template

I need assistance with parsing JSON and presenting the response in a tabular format using Jade. Can you help me display the key-value pairs in two separate columns? Node.js exports.postMQinput = function(req, res) { req.assert('name', 'Q ...

Ways to add AJAX information to select2

I am currently utilizing a select2 dropdown feature and I am attempting to configure it in such a way that it dynamically displays the leads based on the JSON response. As you can observe in the image provided below, the text correctly yields a JSON array ...

Is there a way to rearrange the selectpicker selection based on the user's choice?

I'm in the process of setting up a selectpicker that allows users to choose multiple options from a dropdown list. The challenge is that the values extracted by my backend need to be in the order of user selection, rather than the original order of th ...

The absence of the dark class in the body is still allowing the impactful influence of Tailwind

I set up a ThemeContext in my NextJS project to switch between light and dark themes on my website. However, I encountered an issue where elements that have the "dark:" prefix in their class names apply the dark theme instead of the initial light theme whe ...

Running npm commands, such as create-react-app, without an internet connection can be a

Currently, I am working in an offline environment without access to the internet. My system has node JS installed. However, whenever I attempt to execute the npm create-react-app command, I encounter an error. Is there a workaround that would allow me to ...

"How can you enhance the performance of JavaScript and CSS in a Chrome Extension without using exclude_matches/globs or excluding domains

I have been in the process of creating a Chrome Extension, and unfortunately, when I tried to make it work on specific URLs, I encountered an issue. While Chrome has options like exclude_matches and exclude_globs for this purpose, there seems to be a bug i ...

Achieving a sticky scrollbar effect in CSS/JavaScript for scrolling within nested divs

I am trying to create a table with vertical scrolling for the entire table content. Additionally, I need two columns within the table to be scrollable horizontally, but the horizontal scrollbars disappear when the vertical scrollbar is present. How can I k ...

Retrieve data from the database at the optimal time interval, and halt the process once the data has been successfully received

I'm new to this, so please bear with me :) What is the easiest way to check for, fetch, and utilize newly received data from a MySQL database? The database is constantly updated through an external API. Ideally, I would like to capture the data as i ...

Pass information from ColdFusion to jQuery

I'm attempting to achieve a similar result as this, but I believe the syntax is not quite right: <cfset details = '{ name: "name", address:"address"}' /> <img data-details='#details#' onClick="DisplayDetails()" /> &l ...

Is there a way to access the initial item in a JavaScript array?

Recently, I've been delving into the world of javascript and encountered a task that involves removing the first item from an array. Solution One function getFirst(arr, item) { arr.push(item); var removed = arr.shift(); return removed; } S ...

What is the best way to declare a global variable while making an asynchronous call using AngularJS?

Is there a way to utilize the single_video variable outside of the controller function? The issue arises when attempting to access it in the second console.log, as it returns an 'undefined' error due to asynchronousity despite successfully printi ...

node-gallery reports: "No albums were discovered"

I am exploring the use of node-gallery in my Node js/Express/Jade project. After following the guidelines provided at https://github.com/cianclarke/node-gallery, I encountered an issue when attempting to access the page localhost:3000/gallery: {"message" ...

Transmit a pair of data values to the ajax request

How can I send two parameters to my JavaScript and retrieve them in a PHP file? Here is my HTML: <form method="post" action="testButtonSup.php"> <p> Please choose the service:<br /> <input type="radio" n ...

Step-by-step guide on transferring form data from an Ionic application to parse.com MBaaS through the REST API

Today is my first day with Ionic/Angular, and I'm diving in out of necessity. I've been using tutorials and documentation to create a demo/test app that submits data to the Parse.com MBaaS service. However, I seem to be stuck somewhere and clue ...