I was wondering if there is any way to rewrite the for
loop using filter()
.
What if I say you can avoid for
loop completely.
Yes, you can avoid loop by letting jQuery do that for you. jQuery accepts multiple comma-separated selectors and internally iterate over each selector and perform operations.
generators
is an array of elements, this array elements can be joined with ,
as glue, to create the selector.
Let's say, we have an array var selectors = ['#someId', '.myClass', 'tag']
and we want to add a class to all these selectors. We can iterate over the array and add the class to each element individually or we can combine the array elements somehow to create a comma-separated string and pass this to jQuery
as selector.
$(selectors.join(', ')).addClass('magic');
selectors.join(', ')
will join the array elements by ,
, thus giving '#someId, .myClass, tag'
which is valid selector and can be passed to jQuery
and any method defined on jQuery
prototype can be called on it.
Same logic can be used, in your case.
As join
will add the glue between the elements of array, the prefix and suffix need to be concatenated.
The selector can be created using
'.generatorContainer[data-generator="'
+ list.join('"], .generatorContainer[data-generator="')
+ '"]'
Line #1 is the prefix
Line #2 will give firstElement"], .generatorContainer[data-generator="secondElement"], ..., .generatorContainer[data-generator="lastElement
Line #3 will add suffix to make the selector valid.
With this, the code will be
var selector = '.generatorContainer[data-generator="' + list.join('"], .generatorContainer[data-generator="') + '"]';
$(selector).doMagic(); // He He
To add to the complexity, not()
can be used to exclude elements
$('.generatorContainer').not(selector).hide(); // Hide those except in array
$(selector).show(); // Show only those in array
join
on array to create a comma-separated selector and avoidfor
loop completely. You can use'.generatorContainer[data-generator="' + list.join('"], .generatorContainer[data-generator="')
\$\endgroup\$for
orwhile
loops are the quickest way iterate over any array. To further improve performance use the DOM API to query for elements rather than jQuery. \$\endgroup\$