Find the closest number in a table to a specific number

Viewed 76

I have a table of numbers that I want to find the closest number to a particular number and change its color. Friends, how can this be done?

function Cf(){
  $("td").each(function () {
      let v=$("#s1").val()
      if(this.innerHTML<v){
         this.style.color="red"
      }else{
         this.style.color="black"
      }  
  })
 }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="table">
  <tr>
    <td>100</td>
    <td>70</td>
    <td>30</td>
    <td>50</td>
    <td>10</td>
    <td>50</td>
    <td>90</td>
    <td>20</td>
    <td>40</td>
  </tr>
</table>

<select id="s1" onchange="Cf()">
  <option value="83">83</option>
  <option value="23">23</option>
  <option value="73">73</option>
  <option value="63">63</option>
  <option value="53">53</option>
</select>

1 Answers

function Cf() {
    let innerhtml = [];
    $("td").each(function () { 
        innerhtml.push(this.innerHTML)
    });

    const needle = $("#s1").val();
    const closest = innerhtml.reduce((a, b) => {
        return Math.abs(b - needle) < Math.abs(a - needle) ? b : a;
    });

    $("td").each(function () {
        if (this.innerHTML === closest) {
            this.style.color = "red"
        } else {
            this.style.color = "blue"
        }
    });
    console.log(closest)

}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="table">
   <tr>
     <td>100</td>
    <td>70</td>
    <td>30</td>
    <td>50</td>
    <td>10</td>
    <td>50</td>
    <td>90</td>
    <td>20</td>
    <td>40</td>
  </tr>
</table>

<select id="s1" onchange="Cf()">
   <option value="83">83</option>
   <option value="23">23</option>
   <option value="73">73</option>
   <option value="63">63</option>
   <option value="53">53</option>
</select>

Related