Home > Back-end >  concise way to count amount of different data-attribute values with jQuery
concise way to count amount of different data-attribute values with jQuery

Time:10-04

I've a html/js structure and logic that looks somehow like this:

$(document).ready(function(){
  $('input').on('input',function(){
    search($(this).val());
  });
});

const search = (text) => {
  $('.tile').hide();
  
  //TODO get amount of different categories
  //Possibility 1 --> using $.each()...

  $('.tile').filter(function(){
      let category = $(this).data("category");
      
      if( category.indexOf(text) !== -1 )
      {
        return $(this);
      }
  }).show();
};
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<input type="search" />

<hr>

<div  data-category="tee">Tee</div>
<div  data-category="coffee">Coffee</div>
<div  data-category="coffee">Coffee</div>
<div  data-category="tee">Tee</div>
<div  data-category="soda">Soda</div>
<div  data-category="tee">Tee</div>
<div  data-category="tee">Tee</div>

Now I want to know when only one category is left after filtering.

There is already an answer to this problem here, but I wonder if there is a more concise way without using $.each()... everytime I search for a value.

I feel like there must be something like $('[data-category]').length in jQuery.

CodePudding user response:

You could add something like this:

var n = $('.tile:visible').map(function(){
  return $(this).attr("data-category")
}).get();
n = $.unique(n)
if (n.length == 1) {
  console.log("one category is left")
}

Demo

$(document).ready(function() {
  $('input').on('input', function() {
    search($(this).val());
  });
});

const search = (text) => {
  $('.tile').hide();

  $('.tile').filter(function() {
    let category = $(this).data("category");

    if (category.indexOf(text) !== -1) {
      return $(this);
    }
  }).show();
   
  var n = $('.tile:visible').map(function(){
    return $(this).attr("data-category")
  }).get();
  n = $.unique(n)
  if (n.length == 1) {
    console.log("one category is left")
  }
};
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<input type="search" />

<hr>

<div  data-category="tee">Tee</div>
<div  data-category="coffee">Coffee</div>
<div  data-category="coffee">Coffee</div>
<div  data-category="tee">Tee</div>
<div  data-category="soda">Soda</div>
<div  data-category="tee">Tee</div>
<div  data-category="tee">Tee</div>

  • Related