Discovering the variable name that holds the maximum number following the usage of Math.max()

Let's assume we have the following variables set:

var number1 = 48;
var number2 = 420;
var number3 = 39;

If we want to determine the highest value among them, we can use:

let maximumValue = Math.max(number1, number2, number3);

What if we want to know which specific variable holds the max value? In this case, we are only dealing with 3 variables, but what about a scenario with 20 or even 500 variables. We need to efficiently identify the max value along with its corresponding variable name.

Answer №1

It's impossible to retrieve the variable name in JavaScript functions as only values are passed, but there is a solution using arrays:

var numbers = [48,420,39];

const index = numbers.indexOf(Math.max(...numbers))

console.log(`The max value is at the ${index+1}th position in the array`)

You can also achieve this with objects:

var num1 = 48;
var num2 = 420;
var num3 = 39;

var numbers = {num1, num2, num3}

const maxVal = Math.max(...Object.values(numbers))
const key = Object.keys(numbers).find(key => numbers[key] === maxVal)

console.log(key, maxVal)

Answer №2

When utilizing the var keyword, the variable becomes bound to the window object. This allows you to loop through the window object and retrieve the variable names. By following a consistent naming convention, such as using num1, num2, etc., you can create an if statement to verify if num is included in the key.

var num1 = 48;
var num2 = 420;
var num3 = 39;

var max = Math.max(num1, num2, num3);

let s = Object.keys(window).filter(key => {
      if (key.includes("num")) {
          return window[key] == max
        }
      });

console.log(s)

Answer №3

A different approach utilizing the reduce method

function findLargestNumber(numbers) {
  return numbers.reduce((acc, number, index) => {
    if(number > acc.value) {
      acc.value = number;
      acc.index = index;
    }
    
    return acc;
  }, {value: null, index: null});
}

let numbers = [48,420,39];
const largest = findLargestNumber(numbers);

console.log(largest);

Answer №4

O(n) Approach

function findMaxIndex(arr) {
  let maxVal = -Infinity, index = -1;
  
  for (let i = 0; i < arr.length; i++) {
    if (arr[i] > maxVal) {
      maxVal = arr[i]
      index = i
    }
  }
  return index
}

const array = [48, 420, 39]
let result = findMaxIndex(array)
console.log(result) // Output will be 1 as the index of 420 is 1

Answer №5

To simplify the comparison process, I recommend storing the values in an array or list and utilizing a for loop. Here's an example to demonstrate this:

let numbers = [48, 420, 39]; 
let maximum = Math.max(numbers[0], numbers[1], numbers[2]);
for(let index = 0; index < 3; index++){
    if(numbers[index] == maximum){
        console.log("The largest number is at index" + index)
    }
}

This approach should streamline the comparison task effectively.

Answer №6

initialize an array that will store the variable name along with its respective value like so:

let variables = 
[
  {"varName":"num1",
   "value": 50},
   {"varName":"num2",
   "value": 51},
   {"varName":"num3",
   "value": 52},
]

next, iterate through the array to identify the maximum value and its corresponding name as shown below:

 function findMaxValueAndName(arr) {
    let i;
   
    // Set the initial maximum element
    let maxVar = arr[0];

    // Loop through array elements starting from the second one
    for (i = 1; i < arr.length; i++) {
        if (arr[i].value > maxVar.value)
            maxVar = arr[i];
    }
     
  return maxVar;
}

let variables = [{
    "varName": "num1",
    "value": 50
  },
  {
    "varName": "num2",
    "value": 51
  },
  {
    "varName": "num3",
    "value": 52
  },
]

function findMaxValueAndName(arr) {
  let i;

  // Set the initial maximum element
  let maxVar = arr[0];

  // Loop through array elements 
  for (i = 1; i < arr.length; i++) {
    if (arr[i].value > maxVar.value)
      maxVar = arr[i];
  }

  return maxVar;
}

console.log(findMaxValueAndName(variables));

Answer №7

Your variables can be properties of an object, members of a function scope, or reside in a module.

  1. If your variables are properties of an object, including the global/window object, you can use Object.keys() and .reduce() to find the variable with the maximum value.

    var object = { var1: 1
                 , var2: 2
                 , var3: 3
                 },
        maxVar = Object.keys(object).reduce((prev, curr) => object[prev] > object[curr] ? prev : curr);
    
    console.log(maxVar); // "var3";
    

    You can also use a for in loop for this purpose.

  2. On the other hand, if you want to define your variables within a function scope, it is recommended to create a constructor function where you declare your variable names as this.var1 ... this.varN to access them from the instantiated object, similar to the previous method.

  3. To keep your variables organized, place them in a module like so:

    export let name1 = ..., name2 = ..., ..., nameN; // you can also use var and const  
    

    You can then import these variables into your code using:

    import * as object from "./myModule";
    

    and follow the steps outlined in paragraph 1 above.

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

Switch the placement of two DIV elements by their corresponding IDs

I am attempting to adjust the position of two divs using jQuery, but I seem to be a bit confused as they are already swapping positions. However, when they do swap, it results in a duplication of the field. I have tried using both insertBefore and insertA ...

Using jQuery Plugin for Date Operations

I am in search of a jQuery tool that can assist me with date manipulations, such as: 1) Adding a specific number of days to a date and obtaining a new Date. 2) Determining the week of the year for a given date. 3) Calculating the number of days between two ...

Tips for customizing the appearance of a single plot within a time series chart using FusionCharts or FusionTime

I've implemented a time series line graph using FusionCharts in the following code snippet: const MyChart = () => { const schema = [ { name: "Category", type: "string" }, { ...

E2E testing on mobile devices with the Webdriver JavaScript client API from the official source

In the Appium documentation, it is noted that the wd.js Webdriver Javascript bindings are mentioned instead of the official bindings. While Appium can work with both clients, the wd.js offers specific mobile methods like touch and shake which are not prese ...

To access a restricted selection of images stored in Firebase

Is there a way to load additional images from Firebase by clicking a button? I created a function that looks like this: onLoadMore() { if (this.all.length > 1 ) { const lastLoadedPost = _.last(this.all); const lastLoadedPostKey = lastLoadedP ...

Can someone explain how I can effectively test the internal workings of a promise using Jasmine?

Within the Angular component I am testing, there is an async promise that I am struggling to examine. The code inside the 'then' block is crucial for my testing purposes, but I cannot seem to access it. angular.module('Ls', [ ]) funct ...

Using a function as an argument to handle the onClick event

I have a function that generates a React.ReactElement object. I need to provide this function with another function that will be triggered by an onClick event on a button. This is how I call the main function: this._createInjurySection1Drawer([{innerDra ...

How to modify attributes using ng-content in Angular 2

Looking for a way to modify the attribute of the top div within the ng-content in my code. Here's an example snippet: <ng-container> <ng-content select="[content-body]"></ng-content> </ng-container> For instance, I want t ...

conversion of markdown into a JSON object

Upon importing a markdown file into a node module using a webpack loader, I encountered an issue. The imported file is a text book with chapters separated by h2 tags. I am seeking a solution to convert this markdown file into a JSON object where each h2 t ...

Is there a way to modify a document without altering its original location?

I attempted to load an entire page using ajax, with the doctype and html tags removed. However, when I tried setting it with the following code: document.documentElement.innerHTML=xmlhttp.responseText; Google Chrome returned an error message: An invalid ...

Obtain text content using JQuery and AJAX rather than retrieving the value

I am struggling with a dynamic table that needs to perform calculations before submitting, requiring the presence of values. However, I want to submit the text from the options instead of the values. Despite trying various approaches, none of them seem to ...

Issues with Angular radio buttons are causing them to not be selected properly

When it comes to radio buttons, they should be checked based on certain conditions. <input data-ng-checked="user.contract1 || user.contract2" data-ng-model="user.agreed" type="radio" data-ng-value="true"> Yes <input data-ng-checked="!user.contrac ...

Exploring the Node Promise Chain: Utilizing Local Functions and Managing Multiple Value Passing in a Code Review

Upon reviewing the code provided, several questions have arisen: #1 I am curious about the best way to make the values returned by the bluebird.all functions accessible in subsequent functions. Is using the this-context a viable option without declaring t ...

React Quill editor fails to render properly in React project

In the process of developing an application in Ionic React, I am in need of a rich text editor that can save data on Firestore. Despite initializing the editor as shown below and adding it to the homepage component, it is not rendering correctly although i ...

Obtaining the final field with the $in operator in Mongoose

I need to retrieve all person records that fall within a time frame specified by start and end dates, and have a place ID of either 1 or 2. Below is the query I am using: Person.find({ time: { $gte: start, $lt: end ...

Using jQuery, is it possible to retrieve the product name and image dynamically?

I'm currently working on implementing an add to cart functionality using jQuery. When the add to cart button is clicked, the product name and image should be displayed. I can achieve this statically but I need help figuring out how to dynamically retr ...

Slightly puzzled by the declaration of `var app = express()`

After going over the documentation, I'm still struggling to grasp why we store express() inside an app variable. I attempted to call methods using express().get and .post directly, but was unsuccessful. Why is that? Why doesn't it function in t ...

Encasing the app component with a context and encountering the issue: TypeError - (destructured parameter) does not have a defined value

My goal is to wrap all components under the app in a context to provide specific functionalities (as evidenced by my UserContext component). import React, { useState, createContext, useContext } from 'react' const Context = createContext(); exp ...

Testing Ajax code encounters error

Currently, I am running a code test with Jasmine and setting up a mock object for the ajax method. spyOn($,'ajax').and.callFake(function(e){ console.log("is hitting"); }) In order to test the code snippet below: $.ajax({ url: Ap ...

I encounter difficulty utilizing assets within my React application

Currently, I am in the process of developing a React application for practice purposes. However, I have encountered an issue with using images and audio files stored in the assets folder. Despite my attempts to import them into the project, I have been uns ...