Get Two Lowest Values From A Table With Jquery
I have a table:
Solution 1:
First of all, check the Fiddle Demo
Consider your HTML, here is my css & js solution:
javascript
var tds = $('td.value');
var arr = $.makeArray(tds);
arr.sort(function(a,b){
returnparseInt($(b).text()) - parseInt($(a).text());
});
$(arr[arr.length-2]).addClass('lowest');
$(arr[arr.length-1]).addClass('lowest');
css
td.lowest {background-color:lightgreen;}
Solution 2:
var ok = $('table tr td:last-child').map(function () {
return $(this).text();
}).get().sort(function (x, y) {
return x - y
});
alert(ok[0] + ' - is the smallest');
alert(ok[1] + ' - is the 2nd smallest');
Solution 3:
Try
var map = {}, array = [];
var $tds = $('table tr').slice(1).find('td:last-child').each(function () {
var value = +$(this).text();
if (map[value]) {
map[value].push(this);
} else {
map[value] = [this];
array.push(value);
}
})
array.sort(function(a1, a2){
return a1 - a2;
});
$tds.filter(function () {
return $.inArray(+$(this).text(), array) < 2;
}).css('color', 'red')
Demo: Fiddle
Solution 4:
var values = [],
tds = $("table tr").find("td:last");
tds.each(function(){
$(this).data("val",$(this).text());
values.push(parseInt($(this).text()))
})
values.sort(function(x,y){return x > y});
tds.each(function(){
if($(this).data("val") == values[0] || $(this).data("val") == values[1])
$(this).css("color","red");
})
values[0] and values[1] will be smallest and second smallest values respectively.
Solution 5:
This should do the trick:-
var values = $('td:last-child').sort(function(a, b) {
return $(a).text() - $(b).text();
}).slice(0, 2).css('color', 'red').map(function() {
return $(this).text();
}).get();
So, sort each td:last-child
by its text()
value (low to high), then use slice()
to get the first two elements. Apply the css()
to these elements, then use map()
to return their text()
, which will be assigned to var values
Here's a fiddle
Name | Id | Value |
---|---|---|
Post a Comment for "Get Two Lowest Values From A Table With Jquery"