Skip to content
Advertisement

Creating an array from values in a loop

I have a loop that looks like this:

JavaScript

Inside of my loop I want to ad a condition that says “If this title is not equal to NONE, add this to an array with all the others. See below my note in the code:

JavaScript

Basically what I want to do is, all the “selectionItemTitle” that passes the conditon needs to be added to an array so I can use that array some place else.

Is this even possible?

Quick note: The reason why I am using a loop, is because I have lots of other code in it (the above is just an example). So I really want to stick to the loop.

Advertisement

Answer

If I understand the question correctly, you can create your array and then add to it with push, see comments:

JavaScript

But that’s if you want to keep the forEach. You could use filter instead, still doing the other work in the filter callback:

JavaScript

Note the spread so that we turn the NodeList from querySeletorAll into a true array (so it has filter). You can also just use filter directly on the NodeList:

JavaScript
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement