How Can We Compare Three Integers To Find Which One Is Bigger/smaller?
For example; we have three variables: var a = 11; var b = 23; var c = 8; Can we return the variable name of the biggest/smallest value?
Solution 1:
you probably need to use an object or an array to know the variable's name :
var obj = {
'a':11,
'b':23,
'c':8
};
var biggest = '';
for (var name in obj) {
if(biggest !== '' && obj[name] > obj[biggest]) {
biggest = name;
} else if (biggest === '') {
biggest = name;
}
}
return biggest;
Solution 2:
Math.max(a, b, c)
If you have variable number of items in an array:
var arr = [a, b, c];
Math.max.apply(null, arr);
Solution 3:
If it is the variables names of the smallest and largest values that you require, then using ECMA5 methods you could do something like this. You will need to use an object
to be able to get names rather than individual variables.
Javascript
function getNamesSmallestToLargestByValue(thisObj) {
return Object.keys(obj).map(function (name) {
return [name, this[name]];
}, thisObj).sort(function (x, y) {
return x[1] - y[1];
}).map(function (element) {
return element.shift();
});
}
var obj = {
'a': 11,
'b': 23,
'c': 8
};
console.log(getNamesSmallestToLargestByValue(obj));
Output
["c", "a", "b"]
On jsFiddle
As you can see, the returned array will give you the names sorted from smallest to largest by their associated values. Therefore the first element is the name of the smallest value and last element is the name of the largest value.
Solution 4:
var x = parseInt(document.getElementById('sco').value);
var y = parseInt(document.getElementById('sce').value);
var z = parseInt(document.getElementById('scm').value);
if (x > y && x > z)
{
document.getElementById('yo').innerHTML = 'x is greater';
}
else if (y > x && y > z){
document.getElementById('yo').innerHTML = 'y is greater';
}
else{
document.getElementById('yo').innerHTML = 'z is greater';
}
Post a Comment for "How Can We Compare Three Integers To Find Which One Is Bigger/smaller?"