Finding the maximum value among multiple variables in AngularJS

After performing calculations, I have assigned specific values to variables.

    
console.log("Gain_weight is "+ Gain_weight);
console.log("Gain_smoking is "+ Gain_smoking);
console.log("Gain_exercising is "+ Gain_exercising);
console.log("Gain_foodhabits is "+ Gain_foodhabits);
console.log("Gain_parent_heartattack is "+ Gain_parent_heartattack);
console.log("Gain_alcohol "+ Gain_alcohol);
console.log("Gain_occupation "+ Gain_occupation);
console.log("Gain_workinghrs "+ Gain_workinghrs);

In this case, I have values for Gain_weight, Gain_smoking, and more. How can I identify the variable with the highest assigned value using AngularJS?

Answer №1

If you are interested in identifying the highest value, here is a way to achieve that:

var gains = [Gain_wealth, Gain_health, Gain_happiness, Gain_knowledge, Gain_relationships, Gain_career_growth];
var gainLabels = ['Gain wealth', 'Gain health', 'Gain happiness', 'Gain knowledge', 'Gain relationships', 'Gain career growth'];
var maxGainValue = -Infinity;
var maxGainIndex = -1;
for (var i = 0; i < gains.length; i++) {
  if (maxGainValue < gains[i]) {
    maxGainValue = gains[i];
    maxGainIndex = i;
  }
}

console.log('The highest gain recorded is ' + gainLabels[maxGainIndex] + ': ' + maxGainValue);

If your main concern is solely the highest value attained:

var maxGainValue = Math.max(Gain_wealth, Gain_health, Gain_happiness, Gain_knowledge, Gain_relationships, Gain_career_growth)

Answer №2

To ensure optimal performance, it is crucial to select the appropriate data structure. In this scenario, a data structure with total-ordering like a Binary Search Tree or a Skip list would be most suitable. Utilizing a red black tree, such as the one provided in this implementation, simplifies the solution:

var RBTree = require('bintrees').RBTree;
var tree = new RBTree(function(a, b) { return a.gain - b.gain; });

tree.insert({name: 'Weight Gain', gain:1});
tree.insert({name: 'Smoking and Gain', gain:2});
// continue with more insertions...

tree.max();
// => {name: 'Smoking and Gain', gain:2}

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 is the best way to pass a JSON object containing an array of objects to a Spring controller?

Currently, I have set up two domain models in Hibernate using @OneToMany mapping. My goal is to generate a JSON object on the frontend and then transmit it to the Spring MVC controller so that the model data can be automatically set. The main model classe ...

What is the best way to create 2 select boxes that will disable each other if they match, and then automatically choose the second option so they do not match

Is there a way to have 2 select boxes automatically change one option to the second option on one box when they match? Instead of using an "alert", I am looking for a function that can automatically update one option in one of the select boxes if they mat ...

Unable to execute the new firebase on node server

I'm currently watching this google talk. However, I am facing an issue trying to create a firebase object. Following my package.json file, I initiated with: npm install firebase --save Then proceeded with the following steps: let Firebase = requir ...

Preventing the "save" button from being enabled until a change has been made to at least one input field

I have a page with approximately 20 input fields, along with save and register buttons. Is there a way to activate the "save" button only when a change has been made in at least one of the fields? ...

Issue: Trouble with Rotating Tooltips in Javascript

I am facing a challenge with the tooltips on my website. I want to ensure that all tooltips have a consistent look and transition effects, but I am struggling to achieve this. The rotation and other effects applied using javascript are not functioning prop ...

Despite the fact that `ng-show="true"`, it is still hiding due to having the class `ng-hide`

I'm a beginner when it comes to AngularJS, so I may be missing a straightforward solution to my issue. The challenge I'm facing involves working on a form with two inputs - one for the number of doors and the other for the number of windows. I ha ...

What is the reason behind getElementsByClassName not functioning while getElementById is working perfectly?

The initial code snippet is not functioning correctly DN.onkeyup = DN.onkeypress = function(){ var div = document.getElementById("DN").value document.document.getElementsByClassName("options-parameters-input").style.fontSize = div; } #one{ heigh ...

Which architectural style is best to master for developing exceptional JavaScript software?

My familiarity with Model-View-Controller runs deep, having worked with it for years in server-side development using languages like PHP. Now, I find myself diving into JavaScript and embarking on a large project that utilizes SVG, Canvas, and other moder ...

Fill the table with information from a JSON file by selecting options from drop-down menus

I am currently working on a web application project that involves bus timetables. My goal is to display the timetable data in a table using dropdown menus populated with JSON information. While I believe I have tackled the JSON aspect correctly, I am facin ...

What could be causing the return of undefined upon execution?

function updateTitle(title) { title = "updated title"; } var currentTitle = "original title"; currentTitle = updateTitle(currentTitle); console.log(currentTitle) I'm just starting to learn JavaScript and I'm curious about why this code behav ...

`How can I retrieve the previous location path in an AngularJS application?`

Is there a way in AngularJS to check my previous path location from my current one? ...

Could someone assist me in understanding why VScode is displaying an error stating it cannot locate a module?

node:internal/modules/cjs/loader:1051 throw err; ^ Error: The module '/Users/ben/Desktop/GA/unit2/week5/GA_Project_2/QuotaQuest/index.js' cannot be found. at Module._resolveFilename (node:internal/modules/cjs/loader:1048:15) at Modul ...

What is the best way to display "SUCCESS" on the console when a launch is successful, and "ERROR" when it is unsuccessful?

Here is the question: I am delving into Node.js using the Puppeteer library, and I am looking to output "SUCCESS" in the console upon a successful execution, and "ERROR" if it fails. However, I am struggling to grasp how to achieve thi ...

Utilizing "this" in a situation where the function and selector are not combined

When it comes to utilizing this in different scenarios, the results may vary. In example 1, we see that by directly accessing this, we are able to obtain the correct result. $("#my_div").on("click", function () { alert( $(this).attr("id") ) }); Howev ...

Exploring the power of ES6 map function within React stateless components

I have a React application that fetches an array of objects from an API response. I want to display each object's details in an accordion format. Using the react-accessible accordion library, I created a React Stateless Component to achieve this. Each ...

Tips for expanding third-party classes in a versatile manner using Typescript

tl;dr: Seeking a better way to extend 3rd-party lib's class in JavaScript. Imagine having a library that defines a basic entity called Animal: class Animal { type: string; } Now, you want to create specific instances like a dog and a cat: const ...

Trouble Navigating the DOM

Can you assist me in choosing the correct option c? Below is the provided HTML code: <div id="a"> <div id="b"></div> <div id="app7019261521_the_coin_9996544" style="left: 176px; top: 448px;"> <a href="d.com" oncl ...

Saving an array of key-value pairs in local storage

I'm attempting to save an array in local storage using the following code: var tempval = []; tempval['key'] = 1; localStorage.setItem("Message", JSON.stringify(tempval)); However, when I check local storage, it only sho ...

Every variable that has been stored in the local storage

Currently, I am working on an Android application utilizing AngularJS and Ionic framework. To temporarily store data in the app, I am using the $localstorage service. However, despite my efforts to find a proper way to view all the stored variables in $l ...

Here is a way to return a 400 response in `express.js` when the JSON request body is invalid

How can I make my application send a response with status code 400 instead of throwing an error if the request body contains invalid JSON? import express from 'express' app.use(express.urlencoded({ extended: false })) app.use(express.json()) ...