...

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

brandonlee
06-12-2010, 01:55 AM
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;

jmrker
06-12-2010, 08:32 PM
Can you modify this logic to suit your needs?

<html>
<title>Max Number Tie</title>
<script type="text/javascript">

// array to represent 5 answers to the 'c' question (c1-c5)
var c = [2,1,2,0,0];

var str = '';
str += 'Original responses to question "c":<br>';
for (var i=0; i<c.length; i++) { str += 'c'+(i+1)+'='+c[i]+', '; }

var cmax = [];
var maxC = -1e10;
for (var i=0; i<c.length; i++) {
if (c[i] > maxC) { maxC = c[i]; cmax = []; cmax.push('c'+(i+1)); }
else { if (c[i] == maxC) { cmax.push('c'+(i+1)); } }
}
cmax.sort();
str += '<br>Max response: '+maxC+'<br>';
str += cmax.join('<br>');

str += '<br>Priority goes to: '+cmax[0];
document.write(str);
</script>
<body>
</body>
</html>

brandonlee
06-20-2010, 06:34 AM
Can you modify this logic to suit your needs?

<html>
<title>Max Number Tie</title>
<script type="text/javascript">

// array to represent 5 answers to the 'c' question (c1-c5)
var c = [2,1,2,0,0];

var str = '';
str += 'Original responses to question "c":<br>';
for (var i=0; i<c.length; i++) { str += 'c'+(i+1)+'='+c[i]+', '; }

var cmax = [];
var maxC = -1e10;
for (var i=0; i<c.length; i++) {
if (c[i] > maxC) { maxC = c[i]; cmax = []; cmax.push('c'+(i+1)); }
else { if (c[i] == maxC) { cmax.push('c'+(i+1)); } }
}
cmax.sort();
str += '<br>Max response: '+maxC+'<br>';
str += cmax.join('<br>');

str += '<br>Priority goes to: '+cmax[0];
document.write(str);
</script>
<body>
</body>
</html>

Thanks a ton this helps out tremendously!

jmrker
06-20-2010, 02:19 PM
Thanks a ton this helps out tremendously!

You're most welcome.
Happy to help.
Good Luck!
:)