MeltingDog
MeltingDog

Reputation: 15424

Detect variable with largest value without using array?

I need to find which variable has the largest value.

Normally I would do something like:

var Dimensions = [Height, Length, Depth];

var biggestSide = Math.max.apply(Math, Dimensions);

But I need to do something with the variable after this.

Is there anyway to identify the var with the largest value without using arrays or a series of if statements?

Upvotes: 0

Views: 85

Answers (2)

Jack Allan
Jack Allan

Reputation: 15004

You could use a switch statement

var biggestSide = Math.max(Height, Length, Depth);

switch (biggestSide) {
     case Height:
         ...
         break;
     case Length:
         ...
         break;
     case Depth:
         ...
         break;
}

After reading your comment:

@mplungjan - in brief, the vars Height, Length and Width and the max values from arrays themselves. I need to identify the array that has the largest value so I can do something with the vars that are pushed to that array. – MeltingDog

I think something like this is what you are after

var maxHeight = Math.max.apply(Math, Height);
var maxLength = Math.max.apply(Math, Length);
var maxDepth = Math.max.apply(Math, Depth);

var biggestSide = Math.max(maxHeight, maxLength, maxDepth);

switch (biggestSide) {
     case maxHeight:
         // Do something with Height
         break;
     case maxLength:
         // Do something with Length
         break;
     case maxDepth:
         // Do something with Depth
         break;
}

Note with ES6 you can use the spread operator instead of the apply function:

var maxHeight = Math.max(...Height);

Upvotes: 1

Amit
Amit

Reputation: 46323

Math.max() accepts as many values as you want. You don't need an array for this:

var biggestSide = Math.max(Height, Length, Depth);

Upvotes: 0

Related Questions