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

Combining load and change events in jQuery at the same time

Often times, I find myself needing to attach a behavior to an element both after it has loaded and after a specific event has been triggered (such as "change"). I believe the most efficient approach would be to combine these actions in one line: $('# ...

How can I store the city name instead of the city id in the database when submitting data from a dependent dropdown select in Ajax PHP?

For the past few days, I have been unable to solve a problem. The issue is as follows: I have a web form with dependent dropdown select boxes where users can choose their city, zip code, and street. However, when the form is submitted, only the city_id ( ...

What is the process for loading JavaScript along with its dependencies?

Imagine a scenario where I have script A that loads another script B: $.getScript('B.js', foo); Now, what if script B also loads an additional script? In that case, I want the function foo to be executed only after both B and its loaded script ...

Firefox Issue: SetTimeout Redirect Function Not Functioning Properly

Working on a page that redirects users to an installed application or a webpage as a fallback. This is implemented using ClientScript.RegisterStartupScript when the page loads, with a Javascript snippet like this: <script type='text/javascript&apo ...

Creating a CSS grid layout with a scrollbar positioned on the left side and content filling from left to right

How can I move the scrollbar to the left while keeping ng-repeat population from left to right? I'm using an ng-repeat to fill a grid that is 3 by X (Width by height). By default, the scroll bar appears on the right side. I want to position it on the ...

Unable to assign an ID to an element in JavaScript, as it will constantly be undefined

Is there a way to automatically generate unique IDs for jQuery objects if they don't already have one? I need these IDs for future requests. I wrote the following code, but it doesn't seem to be working. The ID's are not getting set and the ...

Is it possible to use Docxtemplater.js in a browser without familiarity with Node, Browserify, or npm?

I'm trying to get Docxtemplater.js to function properly on a browser. Unfortunately, I lack knowledge in areas such as Node.js, Browserify.js, "npm", "bower", and other technical aspects commonly found in modern JavaScript libraries. While I do inten ...

What is the best way to conceal a bootstrap directive tooltip in Vue.js for mobile users?

Currently, I'm tackling a project with Vuejs and Laravel. There's a tooltip directive incorporated that relies on Bootstrap's functionality. Check it out below: window.Vue.directive("tooltip", function(el, binding) { // console ...

Leveraging the power of HTML5 alongside Angularjs and Node/Express within the MEAN.js boilerplate framework

I've decided to kickstart my app using the mean.js () boilerplate because of its built-in authentication/authorization features. However, I've hit a roadblock when it comes to incorporating HTML5 into my project. In my Angular app, I've en ...

Tips for making sure AngularJS runs a function and its subfunction sequentially

How do I run the code below to display the details of each flavor and its corresponding ITEM ID in a specific order. Execution Format: Flavor1, Flavor2 -- Getflavors() Flavor1 ITEM1, ITEM2... -- GetItemIDs_ofeachFlavor(MapFlvID) GET ITEM1 DETAILS and ad ...

Exploring the power of Ionic and AngularJS in making secure HTTPS Post Requests

I've been attempting to make a request to an HTTPS server via the post method within my Ionic app, but I keep running into issues. I've tried two approaches so far - one using $http, and the other using $.ajax. Unfortunately, neither method has y ...

Combining two sets of data into one powerful tool: ngx-charts for Angular 2

After successfully creating a component chart using ngx-charts in angular 2 and pulling data from data.ts, I am now looking to reuse the same component to display a second chart with a different data set (data2.ts). Is this even possible? Can someone guide ...

Flask caches JSON files automatically

I am currently working on a visualization app using js and python. The functionality of my app is as follows: There is a textbox in the browser where I input an URL The URL is then sent to Python via Flask In Python, the URL is processed to create ...

distance between the top of the window and divs within an array

I'm having trouble calculating the distance of divs within an array from the top of the window. Whenever I try to run the code, I keep getting an error message saying "player.offset is not a function". Can someone please point out where I am making a ...

Ways to eliminate the absence of the 'Access-Control-Allow-Origin' header in an error message when using a Java-based web-service server

I'm currently working on developing a webservice using Java as the server and Javascript as the client. My goal is to send a Post request with JSON data and receive a Post response with JSON data from the server. However, since the client and server h ...

Adding a distinct key and its corresponding value to an array in Vue for a unique

I am attempting to add key-value pairs into an array while ensuring their uniqueness. Currently, I am trying the following approach: for (const [key, value] of Object.entries(check)) { console.log(`${key}: ${value}`); this.inputFields. ...

Tips for obtaining latency measurements from the DailyMotion player during a live video stream

Is there a way to determine the latency of DailyMotion live video for synchronization with events, such as displaying speaker names alongside the video? I have been utilizing the DailyMotion player API in JavaScript but haven't found any information r ...

Determine the availability of a distant website through AJAX requests

My website runs PHP's cURL to check the online status of 5 different URLs, however, this process tends to slow down the page load time significantly, especially if one of the sites being checked is not working. Someone suggested using jQuery's a ...

Vue composable yields a string value

I am currently using a Vue composable method that looks like this: import { ref } from 'vue'; const useCalculator = (num1: number, num2: number, operation: string) => { const result = ref(0); switch (operation) { case 'add& ...

What is the best way to save the data received from createApi into the Redux store?

Currently, I am faced with the challenge of storing user data (such as name, email, etc.) obtained through the createApi function into Redux store. However, I'm unsure of the best practice to achieve this. In my userApi.js file: export const userApi ...