Javascript argument to pick the largest variable and break a tie if exists

Hi there,

I am trying to pick the larger of 5 numbers and sometimes there is a tie. I would like to prioritize variable c1 if there is a tie. This data is from a quiz I am writing.

var c1 = 2; // Takes priority if there is a tie.
var c2 = 1;
var c3 = 2;
var c4 = 0;
var c5 = 0;

var largest = Math.max(char1,char2,char3,char4,char5);
if (char1 == largest) {
  loadPlayer('1','<?=$flv_1?>');
} else if (char2 == largest) {
  loadPlayer('2','<?=$flv_2?>');
} else if (char3 == largest) {
  loadPlayer('3','<?=$flv_3?>');
} else if (char4 == largest) {
  loadPlayer('4','<?=$flv_4?>');
} else if (char5 == largest) {
  loadPlayer('5','<?=$flv_5?>');
}

I think there is a better way, but the above would work :slight_smile:


var largest = Math.max(c1,c2,c3,c4,c5);

I don’t really see why you want the value of c1 in case of a tie. If c1 and c3 have the same value, as in your example, the largest value will be the same regardless of which one you pick. Or am I missing something?

Yes that is correct. There is more too that variable that I choose though which I think is why I need the arguments for it. Depending on which variable is larger and is prioritized I will be running another function to load a specific video. This is what I have thus far but it ignores if there is a tie. If there is a clear larger value, ie 3, then it chooses that one. But when there is a tie it fails.

if(char1 > char2 && char1 > char3 && char1 > char4 && char1 > char5){
	loadPlayer('1','<?=$flv_1?>');
}
	
if(char2 > char1 && char2 > char3 && char2 > char4 && char2 > char5){
	loadPlayer('2','<?=$flv_2?>');
}
	
if(char3 > char1 && char3 > char2 && char3 > char4 && char3 > char5){
	loadPlayer('3','<?=$flv_3?>');
}
	
if(char4 > char1 && char4 > char2 && char4 > char3 && char4 > char5){
	loadPlayer('4','<?=$flv_4?>');
}
	
if(char5 > char1 && char5 > char2 && char5 > char3 && char5 > char4){
	loadPlayer('5','<?=$flv_5?>');
}

You’re welcome :slight_smile:

Yay! ScallioXTX that works perfect! I like the method because it’s intuitive! I am somewhat new to javascript so it’s hard to think of other possibilities until I have seen or tried other variations. Thanks a ton!