user3577397
user3577397

Reputation: 473

Javascript - Find middle value of user inputted numbers

I'm having trouble figuring this out, and I think there's probably an easy solution but I'm just not wording it correct.

I know how to find the max value of 3 inputted numbers.

largest = Math.max(number1, number2, number3);  // this code finds largest number

I know how to find smallest number

smallest = Math.min(number1, number2, number3); //smallest number

What I can't figure out is how to find the middle number

So when the user puts in 3 numbers, say 9, 6, 12 (in that order)

number1= 9 //first number user entered
number2 = 6 // second number user entered
number3 = 12 // third number user entered

Right now I have code to find the smallest and the largest, 6 and 12. But I don't know how to call the middle. Is there a Math.middle function I can call. I'm not looking for the middle element in an array, I just want the middle value of the 3 numbers I input.

Hopefully that makes sense.

Upvotes: 0

Views: 6019

Answers (3)

John Boher
John Boher

Reputation: 158

Try this approach:

middle = number1+number2+number3 - Math.min(number1, number2, number3) - Math.max(number1, number2, number3);

Upvotes: 3

divyenduz
divyenduz

Reputation: 2027

There is no Math.middle function and I am not sure what you are trying to achieve here but in case you are just looking to find middle number of 3 digits then this can be your answer :-

function middleNumber(a,b,c){
    var arr=[];
    //Fill a array with the values
    arr[0]=a;
    arr[1]=b;
    arr[2]=c;
    //Sort the array and return the middle element
    arr.sort();
    return arr[1]; 
}

alert(middleNumber(1,2,3));

Here is a working example of the same :- http://jsfiddle.net/k0ruk1sq/

Upvotes: 2

benzo
benzo

Reputation: 431

I would use deviation, as input I get some input_array(values which user enter..) and get lenght of this array and devide it at half. This function will return you index of middle element. At the end just return value of that index.

But you have to understand problematic if lenght of array is odd :p.

Upvotes: 0

Related Questions