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:
My regex is working, but I cannot to get the correct repeat count and change the td's color....
x = $("table").find("tr");
text = "";
x.each(function(line){
number = $(this).text();
check = checkNum(number);
console.log(checkNum(number));
if(check.length > 0){
repeats = check[0][1];
text += "Number "+number[check[0]['index']]+" was repeated "+repeats+ " times on line "+line+"<br>";
$('#results').html(text);
$(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);
if(ex){
tempArray.push(ex);
}
return tempArray;
}
Please check this fiddle
Here is functional way to do it (without regular expressions):
$("#results").html(
[].concat.apply(
$.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
else
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;
})
})
).join("<br>")
);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr><td>2</td><td>3</td><td>1</td><td>5</td><td>1</td><td>1</td><td>1</td><td>1</td><td>0</td></tr>
<tr><td>0</td><td>5</td><td>1</td><td>1</td><td>8</td><td>3</td><td>3</td><td>3</td><td>4</td></tr>
<tr><td>0</td><td>4</td><td>1</td><td>5</td><td>8</td><td>7</td><td>6</td><td>3</td><td>4</td></tr>
<tr><td>5</td><td>2</td><td>2</td><td>2</td><td>2</td><td>9</td><td>2</td><td>2</td><td>0</td></tr>
<tr><td>1</td><td>4</td><td>4</td><td>4</td><td>2</td><td>4</td><td>4</td><td>4</td><td>4</td></tr>
</table>
<div id='results'>
</div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With