[Solved] Getting the count of unique values for elements with regex in datatable


Here are 3 versions

  • ES6 with fat arrows
  • ES2015 with function
  • Legacy JS which should run from IE8 or so
const uniqueCount = [...document.querySelectorAll("td[id^=invNumbers]")]
  .reduce((acc, cur) => {
    const val = cur.textContent;
    if (!acc.includes(val)) acc.push(val);
    return acc;
  }, []).length;
console.log(uniqueCount)

// no fat arrows =>

const uniqueCount1 = [...document.querySelectorAll("td[id^=invNumbers]")]
  .reduce(function(acc, cur) {
    const val = cur.textContent;
    if (!acc.includes(val)) acc.push(val);
    return acc;
  }, []).length;
console.log(uniqueCount1)


// Legacy  - not ES2015 or ES6

var cells = document.querySelectorAll("td[id^=invNumbers]"); // supported since IE9 or so
var arr = [];
for (var i = 0; i < cells.length; i++) {
  var val = cells[i].innerText;
  if (arr.indexOf(val) ===-1) arr.push(val);
}
console.log(arr.length)
<table>
  <tbody>
    <tr>
      <td>ABC</td>
      <td></td>
      <td id="invNumbers0">12345</td>
      <td></td>
    </tr>
  </tbody>
  <tbody>
    <tr>
      <td>GHI</td>
      <td></td>
      <td id="invNumbers1">12345</td>
      <td></td>
    </tr>
    <tr>
      <td>MNO</td>
      <td></td>
      <td id="invNumbers2">4566</td>
      <td></td>
    </tr>
    <tr>
      <td>STU</td>
      <td></td>
      <td id="invNumbers3">12345</td>
      <td></td>
    </tr>
    <tr>
      <td>ABC</td>
      <td></td>
      <td id="invNumbers4">2566</td>
      <td></td>
    </tr>
  </tbody>
  <tbody>
    <tr>
      <td>GHI</td>
      <td></td>
      <td id="invNumbers5">4566</td>
      <td></td>
    </tr>
    <tr>
      <td>MNO</td>
      <td></td>
      <td id="invNumbers6">12345</td>
      <td></td>
    </tr>
    <tr>
      <td>STU</td>
      <td></td>
      <td id="invNumbers7">12345</td>
      <td></td>
    </tr>
  </tbody>
</table>

5

solved Getting the count of unique values for elements with regex in datatable