Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select table cells with highest value/s and second highest value/s

I have the following table and need to find

  • one or more td with the class "sum" with highest value (number)
  • one or more td with the class "sum" with second highest value (number)
  • add class "text-bold" to the matching tds

JSFiddle
code

<!DOCTYPE html>
<html>
<head>
<style type="text/css">
.text-bold { font-weight: 700; }
table {
    margin: 16px 0;
    color:#333;
    border-width: 1px;
    border-color: #666;
    border-collapse: collapse;
}
table th {
    border-width: 1px;
    padding: 4px;
    border-style: solid;
    border-color: #666;
    background-color: #FBDD9B;
}
table td {
    border-width: 1px;
    padding: 4px;
    border-style: solid;
    border-color: #666;
    background-color: #fff;
}
</style>
</head>
<body>
    <table id="table-results">
        <tr>
            <th>Question</th>
            <th>inovation</th>
            <th>all-round</th>
            <th>coordination</th>
            <th>keeper</th>
            <th>analytic</th>
        </tr>
        <tr>
            <td>I.</td>
            <td>D=2</td>
            <td>A=1</td>
            <td>E=10</td>
            <td>C=8</td>
            <td>B=4</td>
        </tr>
        <tr>
            <td>II.</td>
            <td>A=6</td>
            <td>C=1</td>
            <td>B=2</td>
            <td>D=5</td>
            <td>E=1</td>
        </tr>
        <tr>
            <td>III.</td>
            <td>E=4</td>
            <td>B=1</td>
            <td>D=3</td>
            <td>A=2</td>
            <td>C=7</td>
        </tr>
        <tr>
            <td>Suma</td>
            <td class="sum">12</td>
            <td class="sum">3</td>
            <td class="sum">15</td>
            <td class="sum">15</td>
            <td class="sum">12</td>
        </tr>
    </table>
</body>
</html>

In the example above the result should look like this

Suma 12 3 15 15 12

Other possible results

Suma 0 0 0 10 0
Suma 12 3 15 7 9
Suma 1 3 15 15 12
Suma 12 3 15 9 12
Suma 4 4 4 4 4

like image 389
Noga Avatar asked Jan 22 '15 13:01

Noga


1 Answers

It's actually a little bit complicated, you have to get an array with the numbers from the .sum elements, then find the highest number, then remove all those from the array, then find the next highest number, and finally target all elements containing those two numbers.

In code, that would look like

var sum = $('.sum');
var arr = sum.map(function(_,x) { return +$(x).text() }).get();
var max = Math.max.apply( Math, arr );
var out = arr.filter(function(x) { return x != max });
var nxt = Math.max.apply( Math, out );

sum.filter(function() {
    var numb = +$(this).text();
    return numb == max || numb == nxt;
}).css('font-weight', 'bold');

FIDDLE

like image 105
adeneo Avatar answered Oct 20 '22 01:10

adeneo