How to use jquery filter with an array?

Asked

Viewed 82 times

0

I’m creating a filter for a gallery, where only the images that match the selected tags are displayed. I found several examples for gallery with single tag. In my case, an image can contain several tags. Ex:

  • Tags: 2018, 2019, yellow, blue, green, red;

  • Image 1: [2019, blue, red];

  • Image 2: [2019, green, red];
  • Image 3: [2018, blue, green];
  • Image 4: [2019, green, yellow];

When selecting a tag, I include it in an array, where everything is working right. My problem is filtering the images through the selected tags.

Ex: I select the tags "2019" and "green".

Using a foreach, the image grouping would be of the type "OR":

var filtro ['2019', 'verde'];
filtro.forEach(function(valor, chave){
  $('.filter').filter('.'+valor).show('3000');
});

With this, is displayed all images containing "2019" OR "green". But I need to group so that all tags match the image with "2019" and "green". I managed using the code below, using "filter" several times in a row:

$('.filter').filter('.'+filtro[0]).filter('.'+filtro[1]).show('2000');

My question is: is there any way to optimize this code, since the amount of tags is undetermined?

1 answer

0

By optimizing you mean improving performance, or just working with an undetermined amount of tags? If you want to filter for an indeterminate amount, just store the filtered elements in a variable, and then use the show only after all filters have been applied.

var filtros = ['2019', 'verde'];
var tags = $('.filter');
tags.hide();

for (var filtro of filtros) {
  tags = tags.filter('.' + filtro);
}
tags.show('3000');
  • It would use indeterminate tags. I managed to work the way it showed, thank you.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.