Rolland Rolland - 2 years ago 73
HTML Question

How to get repeated values sequently on a html table with jQuery, by condition

I'm trying to determine how many times a number was repeated in a table row, sequently.
When 3 or more occurrences is found, I need change the color of td to red, like this:

Expected result:

Expected result

My regex is working, but I cannot to get the correct repeat count and change the td's color....

x = $("table").find("tr");
text = "";

number = $(this).text();
check = checkNum(number);

if(check.length > 0){
repeats = check[0][1];
text += "Number "+number[check[0]['index']]+" was repeated "+repeats+ " times on line "+line+"<br>";
$(this).css('color', 'red');

function checkNum(num) {
var tempArray = [];
num = num.replace(/\s+/g,"_");
exp = new RegExp(/([0-9])\1{2,}/, "g");
ex = exp.exec(num);


return tempArray;

Please check this fiddle

Answer Source

Here is functional way to do it (without regular expressions):

        $.map($("table tr"), function(tr, line){
            return $(tr).children().get().reduceRight(function (acc, td, i) {
                var txt = $(td).text();
                if (txt === acc[0][0]) 
                    acc[0][1] = i; // Extend range
                    acc.unshift([txt, i, i+1]); // Add a new range
                return acc;
            }, [[null, 0, 0]])
            .filter(function (range) { // Get the ranges that are long enough
                return range[2] - range[1] >= 3;
            .map(function (range) { // Map them to strings, and apply the styling
                $(tr).children().slice(range[1], range[2]).css('color', 'red');
                return "Number "+range[0]+" was repeated "+(range[2] - range[1])+ " times on line "+line;
<script src=""></script>

<div id='results'>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download