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

Storing data in a TypeBuffer and then retrieving it from a file can lead to surprising outcomes

Upon executing the following code: var list = new Uint32Array(16); for (var i=0; i<16; ++i) list[i] = i; fs.writeFileSync("list", new Uint8Array(list).buffer); console.log([].slice.call(new Uint32Array(fs.readFileSync("list")))); We anticipate the out ...

Understanding ReactJS's process of batching all DOM updates within a single event loop, ultimately minimizing the number of repaints needed

While perusing an article on DOM updates in ReactJS, I came across the concept of React updating all changes within a single event loop. Having a background in understanding event loops in JavaScript and how they function in core JavaScript, I am curious ...

Looking to access XML file data using Vue.js on the server side?

I am trying to access an XML file located in a specific path on the server side using VueJS without using jQuery. Can you provide me with some ideas or advice? Scenario: 1. The file is stored at /static/label/custom-label.xml. 2. I need to read this file ...

Is it possible to trigger a function dynamically upon checking a checkbox?

I’ve been working on a simple string formatting app using React, diving into hooks as I go. Right now, I’m tackling the part where I need to trigger specific text formatting functions based on checkbox selections. Let's say, if the lowercase chec ...

JavaScript tip: Improve the way you highlight the current navigation page while scrolling by finding alternative methods to using "scrollY > x"

Currently, my webpage layout is divided into 4 sections - HOME, ABOUT, SKILLS, and CONTACT. Below is the JavaScript code I am using to highlight a specific section on the navigation bar based on the scroll position: let home = document.querySelector(" ...

How to extract selected value from a dropdown menu in a React component

Is there a way for me to retrieve the chosen value from the dropdown menu? The select dropdown contains 12 options. My goal is to capture the selected value and then utilize it in handlecolumnchange to manipulate the number of columns added or removed. Des ...

What is the best way to incorporate a popover into a fullcalendar event displayed on a resource timeline in Vue while utilizing BootstrapVue?

I need help adding a popover to an event in a resource timeline using fullcalendar/vue ^5.3.1 in Vue ^2.6.11 with ^2.1.0 of bootstrap-vue. Although I found some guidance on Stack Overflow, the solution involving propsData and .$mount() doesn't feel l ...

Exploring JSON data in AngularJS

After creating a new Angular App, I decided to store some data in a JSON file. My main concerns are where to best store the .json file within the app and how to access it. Currently, I am facing this error in my Chrome console: GET http://localhost:8000/t ...

What is the solution for resolving an Element that implicitly has said it has an 'any' type as the expression of type 'string' cannot be used to index the type?

Having some trouble with TypeScript in my React project and encountering this error message. Error TS7053: Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{ paymentMethod ...

Incorporating middleware in Next.js to remove route protection

Looking to remove the protection for the login page, and here is how my folder structure looks: https://i.stack.imgur.com/klPYV.png This is the middleware I am using: import { NextResponse, NextRequest } from "next/server"; export async functi ...

Is it possible to perform a forEach operation on two separate arrays simultaneously?

I have created two arrays and then utilized a function to assign values to certain variables based on the element clicked in the array. (Refer to the first code snippet) However, I am now looking to execute another function that makes use of these assigned ...

How to send route parameters to a controller function in ExpressJS

I'm currently working on setting up user authentication for my application using passport JS. I am facing a challenge in passing the passport variable between app.js, routes.js, and controller.js. Despite trying various approaches, I have been unsucce ...

What are the best practices for ensuring secure PUT and DELETE requests?

For the backend of my current project, I have a question regarding security measures. As an illustration, one of the tasks involves handling various "/notes" requests. /notes => retrieve all notes belonging to the authenticated user /notes => creat ...

How can I align rectangles with different heights to display side by side using Javascript?

Currently, I am designing a press page for a website where the headlines/articles are displayed in rectangles. To achieve this layout, I am using the following CSS: .press-blocks{ column-count: 4; column-gap: 2em; padding-left: 10%; padding ...

Retrieve an image from the database and associate it with corresponding features or news in PHP

I have retrieved a value from the database, displayed it as an image, and made it a link. So, I want that when a user clicks on the different image, they get the result from the query related to the image. I hope everyone understands. <?php // Connect ...

Is this code in line with commonly accepted norms and standards in Javascript and HTML?

Check out this Javascript Quiz script I created: /* Jane Doe. 2022. */ var Questions = [ { Question: "What is 5+2?", Values: ["7", "9", "10", "6"], Answer: 1 }, { Question: "What is the square root of 16?", Values: ["7", "5", "4", "1"], Answer: ...

jQuery image resizing for elements

I have successfully adjusted the images in the gallery to display one per row for horizontal orientation and two per row for vertical orientation. Now, I am facing a challenge in making the images scalable so they can resize dynamically with the window. A ...

What is the best method for me to filter the values in my array?

I need to add a value to an array based on certain conditions. My code looks something like this: var newEmployee = []; $scope.employees = [{'id':1, 'new':true},{'id':2, 'new':false}{'id':3, 'new&apo ...

How can VueJs effectively update the data fetched using the created function?

When working with the Promise Object, I prefer to utilize the "then" and "catch" functions instead of asynchronous functions for handling responses in a simpler way. This allows me to avoid using await and conditional if-else statements to check the stat ...

Comparing jQuery's min-width and width properties: A guide on eliminating pixels

Exploring some basic jQuery and JavaScript here. When I use the .width() method, I get an integer value. However, when I use .css('min-width'), it returns a value in pixels which makes it challenging to perform calculations. What would be the be ...