Skip to content Skip to sidebar Skip to footer

Getting The Count Of Unique Values For Elements With Regex In Datatable

I have a data table that has a structure like:

Solution 1:

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 ES6var cells = document.querySelectorAll("td[id^=invNumbers]"); // supported since IE9 or sovar 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><tdid="invNumbers0">12345</td><td></td></tr></tbody><tbody><tr><td>GHI</td><td></td><tdid="invNumbers1">12345</td><td></td></tr><tr><td>MNO</td><td></td><tdid="invNumbers2">4566</td><td></td></tr><tr><td>STU</td><td></td><tdid="invNumbers3">12345</td><td></td></tr><tr><td>ABC</td><td></td><tdid="invNumbers4">2566</td><td></td></tr></tbody><tbody><tr><td>GHI</td><td></td><tdid="invNumbers5">4566</td><td></td></tr><tr><td>MNO</td><td></td><tdid="invNumbers6">12345</td><td></td></tr><tr><td>STU</td><td></td><tdid="invNumbers7">12345</td><td></td></tr></tbody></table>

Solution 2:

You could try something like this:

var arr = $('td[id^=invNumbers]').map(function() {
  return $(this).text()
}).get();
var unique = arr.filter(function(v, i, a) {
  return a.indexOf(v) === i
});

Demo

var arr = $('td[id^=invNumbers]').map(function() {
  return $(this).text()
}).get();
var unique = arr.filter(function(v, i, a) {
  return a.indexOf(v) === i
});
console.log(unique);
<scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script><table><tbody><tr><td>ABC</td><td></td><tdid="invNumbers0">12345</td><td></td></tr></tbody><tbody><tr><td>GHI</td><td></td><tdid="invNumbers1">12345</td><td></td></tr><tr><td>MNO</td><td></td><tdid="invNumbers2">4566</td><td></td></tr><tr><td>STU</td><td></td><tdid="invNumbers3">12345</td><td></td></tr><tr><td>ABC</td><td></td><tdid="invNumbers4">2566</td><td></td></tr></tbody><tbody><tr><td>GHI</td><td></td><tdid="invNumbers5">4566</td><td></td></tr><tr><td>MNO</td><td></td><tdid="invNumbers6">12345</td><td></td></tr><tr><td>STU</td><td></td><tdid="invNumbers7">12345</td><td></td></tr></tbody></table>

Post a Comment for "Getting The Count Of Unique Values For Elements With Regex In Datatable"