开发者

Find Minimum Value in a Column

开发者 https://www.devze.com 2023-01-22 07:12 出处:网络
I have an HTML table column containing integers.What\'s the most efficient way to get开发者_开发技巧 the minimum value using JavaScript or JQuery?Using jQuery, you could use the .map() method with the

I have an HTML table column containing integers. What's the most efficient way to get开发者_开发技巧 the minimum value using JavaScript or JQuery?


Using jQuery, you could use the .map() method with the .get() method to get an Array of integers, then .apply() the Array as the arguments for Math.min to get the minimum.

This assumes that you want the first column in the table. Selector may need to change depending on which column you want.

Example: http://jsbin.com/iyiqa3/

var values = $('#myTable tr > td:first-child').map(function() {
    return parseInt( $.text( [this] ) );
}).get();

var minimum = Math.min.apply( null, values );

Without jQuery, try this:

Example: http://jsbin.com/iyiqa3/2/

var values = [];

var trs = document.getElementById('myTable').getElementsByTagName('tr');

for( var i = 0, len = trs.length; i < len; i++ ) {
    values.push( parseInt( trs[ i ].cells[ 0 ].innerHTML ) );
}

var minimum = Math.min.apply( null, values );


Non-jquery answer (and no guarantees it is "the most" efficient, but shouldn't be bad):

var min, rowNo = null;

var a = table.getElementsByTagName("TR");
for (var i=0; i<a.length; i++) {
 var td = a[i].childNodes[columnNo];
 var val = parseInt(td.innerHTML);
 if (rowNo == null || val < min) {
  min = val;
  rowNo = i;
  }
 }


I would go with plain JavaScript, run through each row of the table, look at the column you're interested in and find the minimum:

function getColumnMin(tableId, columnIndex) {
  var table = document.getElementById(tableId);
  var rows = table.getElementsByTagName('tr');

  var min = Infinity;
  for (var i = 0; i < rows.length; i++) {
    var cols = rows[i].getElementsByTagName('td');
    var value = (cols[columnIndex].firstChild.nodeValue | 0); // force to integer value
    if (value < min)
      min = value;
  }
  return min;
}

This assumes that each <td> contains exactly one value and no other HTML tags.

0

精彩评论

暂无评论...
验证码 换一张
取 消