javascript - Compare participants in one column of the table and make sum from other column, js -
i have table. i'd compare participants. if participant have several result points in table, script has return sum of participant's results. , on every participant. table generated database (".$row["pnt"]."
".$row["station"].
"".$row["res"]."
): participant station points
aa some1 1 dd some1 2 aa sm2 3 dd sm2 4 bb sm3 5 ee sm3 6
for example i've recieve such new table:
aa - 4, dd - 6, bb - 5, ee - 6
i've tried so:
$(document).ready(function () { $("body").click(function () { var rows = $("tbody tr"); var jo = []; (var = 0; < rows.length; i++) { (var j = 1; j <= rows.length; j++) { var pnt1 = $(rows[i]).find(".pnt").html(); var stations1 = $(rows[i]).find(".station").html(); var pntr1 = $(rows[i]).find(".res").html(); if (pnt1 == $(rows[j]).find(".pnt").html()) { pntr1 = parseint(pntr1); pntr2 = parseint($(rows[j]).find(".res").html()); jo.push(pnt1, pntr1, pntr2); break; } } } console.log(jo); }); });
but understood i'm on wrong way. please, me. appreicate if 1 me on issue.
updated after comments:
<table id="pntsres"> <thead> <tr> <th>Участники</th> <th>Баллы</th> </tr> </thead> <tbody> <tr><td class="pnt">aa</td><td class="station">aes</td><td class="res">1</td></tr><tr><td class="pnt">dd</td><td class="station">aes</td><td class="res">2</td></tr> <tr><td class="pnt">aa</td><td class="station">science</td><td class="res">3</td></tr> <tr><td class="pnt">dd</td><td class="station">science</td><td class="res">4</td></tr><tr><td class="pnt">bb</td><td class="station">Аэродром</td><td class="res">5</td></tr> <tr><td class="pnt">ee</td><td class="station">aeroport</td><td class="res">6</td></tr></tbody> </table>
first, consider breaking solution 3 functions - 1 extract data html (which questionable practice in itself), 1 transform data, , 1 output new table. way, code more maintainable.
function getdata() { var rows = $("tbody tr"); var data = []; rows.each(function(idx, row){ var pnt = row.find('.pnt').html(), station = row.find('.station').html()), res = parseint(row.find('.res').html()); data.push(pnt, station, res); }); }
then consider second method
// pass output getdata() processdata() function processdata(data){ var groupedkeys = {}; var groupeddata = data.map(function(datum){ var name = datum[0]; var value = datum[2]; groupedkeys[name] = (groupedkeys[name] || 0) + (value || 0); }); var transformeddata = []; object.keys(groupedkeys).foreach(function(key){ transformeddata.push([key, groupedkeys[key]]); }); return transformeddata; }
the last method of course need implemented yourself, there's ton improved here, start.
Comments
Post a Comment