krushio vida krushio vida - 4 months ago 22
Javascript Question

Sum two highest values using reverse() javascript

How do I sum the two highest values from a list of inputs using JavaScript?

I've tried the below, but I get 4 instead of 5:



<table id="tableID">
<tr>
<td> <input name="name" class="compulsory1" type="text" value="1" /> </td>
<td> <input name="name1" class="compulsory1" type="text" value="3" /> </td>
<td> <input name="name2" class="compulsory1" type="text" value="2" /> </td>

<td>
<script type="text/javascript">
var tdsCompulsory = document.getElementsByClassName('compulsory1');
var len = tdsCompulsory.length;
var cDatax = [];
var cData = cDatax.reverse();
sum = 0;
for(var i = 0; i < 2; i++){
cData.push(tdsCompulsory[i].value);
sum += +tdsCompulsory[i].value;
}
alert (sum);

</script>

</td>

</tr>
</table>




Answer

First you find the two highest values, and then sum them together. I'd probably do it something like this:

document.getElementById("the-button").onclick = function() {
    // Get the values as numbers
    var values = Array.prototype.map.call(
        document.getElementsByClassName('compulsory1'),
        function(input) {
            return +input.value; // + converts to number
        }
    );

    // Put them in order *highest* to *lowest*
    values.sort(function(left, right) {
        return right - left;
    });

    // Add the first two
    var result = values[0] + values[1];
    console.log(values[0] + " + " + values[1] + " = " + result);
};
<input name="name" class="compulsory1" type="text" value="1" />
<input name="name1" class="compulsory1" type="text" value="3" />
<input name="name2" class="compulsory1" type="text" value="2" />
<input id="the-button" type="button" value="Run">

More about that Array.prototype.map.call thing in this answer about looping through arrays and array-like things.

But if you specifically want to use reverse, you'd do that after the sort:

document.getElementById("the-button").onclick = function() {
    // Get the values as numbers
    var values = Array.prototype.map.call(
        document.getElementsByClassName('compulsory1'),
        function(input) {
            return +input.value; // + converts to number
        }
    );

    // Put them in order lowest to highest
    values.sort(function(left, right) {
        return left - right;
    });

    // Then reverse that
    values.reverse();

    // Add the first two
    var result = values[0] + values[1];
    console.log(values[0] + " + " + values[1] + " = " + result);
};
<input name="name" class="compulsory1" type="text" value="1" />
<input name="name1" class="compulsory1" type="text" value="3" />
<input name="name2" class="compulsory1" type="text" value="2" />
<input id="the-button" type="button" value="Run">