Let's say I have the following variables:
var num1 = 48;
var num2 = 420;
var num3 = 39;
And I want to know the max value, for that I use:
var max = Math.max(num1, num2, num3);
Is there a way to know that num2 was the max number? This example only has 3 variables, but let's say I have 20 or 500. I need to know the max value and its variable name in the most efficient way.
In the above example, we have used the Math.max () method with int, long, float, and double type arguments. // compare all elements with max // assign maximum value to max max = Math.max (max, arr [i]); In the above example, we have created an array named arr. Initially, the variable max stores the first element of the array.
Summary: in this tutorial, you will learn how to use the MySQL MAX () function to get the maximum value in a set of values. The MySQL MAX () function returns the maximum value in a set of values.
Specify the key column that you want to find the max or min value that other column based on; 2. Choose one calculation that you need. Kutools for Excel: with more than 200 handy Excel add-ins, free to try with no limitation in 60 days.
Math.max () is an ES1 feature (JavaScript 1997). It is fully supported in all browsers: Optional. One or more numbers to compare A number, representing the highest number of the arguments. -Infinity if no arguments are given. NaN if one or more arguments are not a number.
You cannot know the variable name because the variable name is not passed into javascript functions, only the values, but you can have a workaround
with arrays:
var numbers = [48,420,39];
const index = numbers.indexOf(Math.max(...numbers))
console.log(`The max value is the ${index+1}nth value in the array`)
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)
Since you are using var
, it will get binded to the window
object. Then you can iterate over window
object, and get the name of variable. Also, if you follow same naming convention, like num1
, num2
etc, you can use a if condition to check if num
is present in key or not.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With