Jquery:以最低价格保留表格行中的唯一项目?

时间:2011-08-23 14:04:15

标签: jquery

在这个波纹管表格中,我们可以看到两个不同价格的TV和CAR两个项目。我希望以最低价格显示两件商品而不重复重复商品。

样本表:

<table>
  <tr>
    <th>Items</th>
    <th>Price</th>
  </tr>

  <tr>
    <td>TV</td>
    <td>10000</td>
  </tr>

  <tr>
    <td>TV</td>
    <td>15000</td>
  </tr>

  <tr>
    <td>CAR</td>
    <td>750000</td>
  </tr>

  <tr>
    <td>CAR</td>
    <td>450000</td>
  </tr>   
</table>

目标表:

    <table>
        <tr>
            <th>Items</th>
            <th>Price</th>
        </tr>
        <tr>
            <td>TV</td>
            <td>10000</td>
        </tr>
        <tr>
            <td>CAR</td>
            <td>450000</td>
        </tr>   
    </table>

3 个答案:

答案 0 :(得分:1)

试试这个。

var item = {};
$(".myTable td:first-child").each(function() {
    var key = $(this).text();
    var val = $(this).closest("td").next().text();
    if (!item.hasOwnProperty(key) || item[key] - val > 0) {
        item[key] = val;
    }
});
var t ="<tr><th>Items</th><th>Price</th></tr>"
$.each(item, function(k, v) {
    t += "<tr><td>" + k + "</td><td>" + v + "</td></tr>";
});
$(".myTable").html(t);

演示:http://jsfiddle.net/naveen/uknkS/

答案 1 :(得分:1)

这可能不是最优雅的方式,但它可以在IE 8和Firefox中实现您的目标:

$(document).ready(function(){
    var cheapest = new Array();

    //Build cheapest array
    $('table tr').each(function(){
         var key = $(this).children('td:first-child').html();
         var value = $(this).children('td:last-child').html();
         if (key != null &&             //Verifies this is not the header
            (value < cheapest[key] || cheapest[key] ==null) ) {   
              cheapest[key] = value;
         }
    });

    //Hide the rows that don't match
    $('table tr').each(function(){
         var current_row = this;
         var key = $(this).children('td:first-child').html();
         var value = $(this).children('td:last-child').html();
         if( key != null && cheapest[key] != value ){
             $(current_row).hide();
         }
    });
});

答案 2 :(得分:0)

你去吧

正在使用 demo

$(function(){
   var $UniqueTds = []; 
    var $trs = $("table tr:gt(0)"); 

   $("table tr td:first-child").each(function(){
        if($.inArray($(this).text(), $UniqueTds) == -1){
            $UniqueTds.push($(this).text());
        }
   });

   var $tr = null; 
   $.each($UniqueTds, function(i, val){
       $tr = null;

       $trs.filter(function(){ return $(this).find("td:first").text() == val;})
           .each(function(){

               if($tr == null){
                   $tr = $(this);
               }
               else if(parseInt($tr.find("td:last").text()) < parseInt($(this).find("td:last").text())){
                       $tr = $(this);
               }
           });
           $tr.remove();
   });
});


  [1]: http://jsfiddle.net/WLhkU/
相关问题