Exploring Binary Tree Navigation in JavaScript

I'm feeling a bit disoriented with JavaScript. Here is the nested structure that's causing me trouble:

{
    "value": 5,
    "children": [{
        "value": 18,
        "children": [{
            "value": 27,
            "children": []
        }, {
            "value": 4,
            "children": []
        }]
    }, {
        "value": 2,
        "children": []
    }]
}

Is there a way for me to retrieve the highest value in this tree using JavaScript?

Answer №1

For this particular scenario, consider implementing the following solution:

let mainObject = {
    "value": 5,
    "children": [{
        "value": 18,
        "children": [{
            "value": 27,
	    "children": []
        }, {
            "value": 4,
	    "children": []
        }]
    }, {
        "value": 2,
	"children": []
    }]
};

function findMaxValue(obj) {
    let result = obj.value;
    for(let index in obj.children) {
	result = Math.max(result, findMaxValue(obj.children[index]));
    }
    return result;
}

alert(findMaxValue(mainObject));

Additional Reference Link

Answer №2

It seems that the code should resemble this structure.

let topValue = JSONData.value;

findTopValue(JSONData);

function findTopValue(data) 
{ 
   if(topValue < data.value)
   {
     topValue = data.value
   }
   for(let i=0; i<data.children.length; i++)
   {
     findTopValue(data.children[i]);
   }
}

Answer №3

If your object tree structure remains consistent, there is another approach you can take.

Convert the object to a string and use regular expressions to extract all integer values following the pattern "value: {n}", then determine the maximum value.

  var jsono = {
        "value": 10,
        "children": [{
            "value": 22,
            "children": [{
                "value": 33,
                "children": []
            }, {
                "value": 6,
                "children": []
            }]
        }, {
            "value": 8,
            "children": []
        }]
    }
    var maxValue;
    JSON.stringify(jsono).match(/\"value\":\s*(\d+)/g).map(function(value){ return value.match(/(\d+)/g).map(function(value){ maxValue =  Math.max(maxValue || 0,value);});});
    alert(maxValue);

http://jsfiddle.net/51R7q/3/

Answer №4

I'll provide guidance on the concept, but I won't write out the code for you. Essentially, the process is similar across different programming languages.

To access JSON data using JavaScript, you navigate through each right child node until reaching the end node.

How can JavaScript be used to retrieve information from JSON?

var tree = 
{
  parent : [
    {
      //details of child1
    },
    {
      //details of child2
    },
  ]
}

To access keys in a JSON structure, utilize tree.<key> (dot) or tree['key']. For example, tree.parent or tree["parent"].

When accessing elements in an array, use indices. As the 'parent' is an array, children can be accessed with tree.parent[0] or tree['parent'][0].

In terms of visual distinction between JSONs and arrays, I personally prefer the dot notation method.

Furthermore, it's necessary to differentiate between right and left children. You might establish a convention where the right child is at the [0] index in the array or include another indicator per node specifying whether it is a right or left child.

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

Using a JavaScript function to post the input value and then displaying it through PHP

I am striving to create an input field that will capture the value of what is typed and display it. The JavaScript function is designed to retrieve the value of the input box two seconds after the user stops typing and then post it. However, the issue lies ...

Update the choices in a select dropdown based on the data selected in another form's select field in real-time

Do you think it can be done? If so, how exactly? I've been looking for an example but haven't found anything yet. (I did come across a case of updating options dynamically based on another select field's data within the same form). ...

Comparing Angular 5 with --aot and Angular 5 with --aot=false configuration settings

I am having an issue with my Angular application using Angular 5.0.0 and rxjs ^5.5.2. When I run the command ng serve --aot=false, everything works fine. However, when I use ng serve --aot, I encounter the following error: core.js:1350 ERROR Error: Uncaug ...

Making changes to an input field can impact other elements when using the v-model directive

I am facing an issue with a cart setup where the quantity of all products are being updated when I increase the quantity of one product. How can I prevent this and only update the quantity of the selected product? <div v-for="(product, index) in cartPr ...

"Identify the protocol name (string) based on a specific port number in TCP/UDP communication

Is there a built-in function in any web-oriented language to return protocol names based on port numbers? For example, if we have the following code: protocol = get_protocol_name(22) print protocol We would expect it to print out "ssh". A more detailed ...

Unfortunately, Protractor does not support MouseMove in Firefox browser

I'm fairly new to using protractor and selenium. I've been attempting to replicate the mouse hover action on a button and retrieve values like the position of the mouse pointer and background colors. When I use mousemove, it works perfectly in Ch ...

Display PickerIOS when a button is clicked in a React Native application

I am a beginner with the react framework and I'm trying to implement a PickerIOS component on button click. However, I'm having trouble understanding how to call other classes upon an event. I found this code snippet on the React Native site: v ...

The switch statement within Angular returns null when using getElementById()

In my single page application, I am using ng-switch to switch between different 'pages'. One of these pages contains a modal that is opened using the following function: var modal = document.getElementById('myModal'); vm.openModal = fu ...

Generating an Angular JSON object on the fly

I currently have a JSON object structured in the following format. Although it's hardcoded at the moment, I'm looking to dynamically generate this JSON by looping through another object. The second object should be iterated over in order to cons ...

What could be causing this Javascript code to not increase by 1?

I previously had a piece of code that effectively incremented and decremented the input value by 1 whenever the + or - buttons were clicked. I made some changes to the design recently, and now I'm struggling to target the input element. Any assistance ...

implementing ko.renderTemplate in a custom binding

I am interested in using named templates with a custom bindingHandler in knockout, but I have encountered an issue where the viewModel passed into the custom binding does not include the context properties of $root, $parent, $component, etc., which are nec ...

Need help with TypeScript syntax for concatenating strings?

Can you explain the functionality of this TypeScript syntax? export interface Config { readonly name: string readonly buildPath: (data?: Data) => string readonly group: string } export interface Data { id: number account: string group: 'a&a ...

The Android Login feature is displaying a JSON error message stating "Error: No value for Error

Currently, I am working on a straightforward Android project centered around Login and Registration. One of the key steps involves sending an app key token via JSON to access the Login Service. However, each time I attempt to log in, an error is triggered ...

Tips for ensuring a watcher only runs once in each digest cycle, regardless of how many times the property is modified

I am facing an issue with my function $scope.render() that relies on the value of $scope.myProperty to render a chart. Whenever myProperty changes during a digest cycle, I need to ensure that $scope.render() is called only once at the end of the digest cyc ...

Updating and Preserving Content in Angular

I've encountered an issue while working on a code that allows users to edit and save a paragraph on the screen. Currently, the editing functionality is working fine and the save() operation is successful. However, after saving, the edited paragraph do ...

Retrieving various properties of an object by matching IDs and displaying them without repeated reductions

I'm interested in finding a more efficient way to retrieve properties from a reduced object within a Vue component or wrapper DOM element. Let's say I have these two data objects in my component: player: [{ active: true, id: 0, name: &q ...

PhoneGap switches up the error type with each consecutive run

Why does PhoneGap change errors after every time it is compiled? Sometimes it runs without any issues, but then the same code throws strange errors like parse error or function not found, even though no changes were made to the code. Here is the code that ...

MongoDB query to retrieve blocked user data using JSON syntax

My collection consists of three different Users' posts, and in my Views Session (HTML, CSS) Part, I am attempting to retrieve the post. However, I need to filter out the two posts posted by other users because I have a blocking functionality in my Vie ...

jQuery is in a constant state of indecision when it comes to determining the best way to manage buttons

A straightforward scenario. When a checkbox is checked, it activates a disabled button. Unchecking the box disables the button again. Sample Code: jQuery -> $('#subscribe_button').attr('disabled','disabled') $("[name= ...

Woops! Looks like there's an issue - the property 'url' is not defined and cannot be

I am currently working on fetching data from a REST API using angular2, and everything seems to be going smoothly. However, I have encountered an error that only appears in the console when calling {{content.img.url}}. Interestingly, the code executes fine ...