Iterating through specific elements of an array with filter() I have the following code which iterates through some divs of an array to show() them. I was wondering if there is any way to rewrite the for loop using filter(). Will this have a better performance over my initial code?

var selectEnabledGenerators = function(generators) {
    //List of generator indexes to show
    var list = generators;
    var allGenerators = $(".generatorContainer");
    //Hide all generators
    allGenerators.hide();
    //maybe use filter here?
    for (var i = 0, max = list.length; i &lt; max; i++) {
        $(".generatorContainer[data-generator=" + list[i] + "]").show();
    }
};
This is kinda pointless:

var list = generators;


The generators argument is already a local variable. I get you might want to call it by a different name, but in that case the parameter should be called generatorIndices or something more descriptive.
The allGenerators variable isn't necessary. It could be, but you're not reusing it. You could just write $(".generatorContainer").hide();.


And yes, you can use jQuery's filter. You've already found all .generatorContainer elements once, so that's the collection you want to filter.

I'd probably just do:

var selectEnabledGenerators = function (generatorIndices) {
    var containers = $(".generatorContainer").hide();
    generatorIndices.forEach(i =&gt; containers.filter(`[data-generator=${i}]`).show() );
};