Jump to content

Looping through certain members of a group


ForgeableSum
 Share

Recommended Posts

Suppose I have a group which contains all of the sprites in my game. Several of these sprites, when they become selected by my mouse, get the property "selected = true."

 

Now every time I want to access those selected, I can loop through them like this:

Sprites.forEach(function(sprite) {if(sprite.selected == true) {// do stuff}}); 

This works fine for my purposes but I'm wonder if there's a better way to do this. I shouldn't have to loop through ALL sprites just to get the sprites I want. I should be able to access the sprites directly, like if I were to put them in their own group (e.g. selectedSprites):

selectedSprites.forEach(function(sprite) {// do stuff}); 

The problem with putting them in their own group (like above) is that it removes them from the Sprites group and I can't have that. I need them to be in both Sprites and spritesSelected. I don't think making the spritesSelected group a child of Sprites group will work either, since looping through Sprites will not give me selectedSprites as well. What do I do here? 

Link to comment
Share on other sites

I suspect filter will be comparable in speed as it still has to check the whole array. If you want to have a way to only iterate through relevant items, you should probably add them to a 'selected' array either instead of or in addition to setting their selected property. This will speed up iteration but will slightly reduce performance when selecting/deselecting items, as you'd have to then manipulate an array to add or remove them. If you're iterating lots and selecting/deselecting little (like I would expect) then this will be the best way to do it.

Link to comment
Share on other sites

I suspect filter will be comparable in speed as it still has to check the whole array. If you want to have a way to only iterate through relevant items, you should probably add them to a 'selected' array either instead of or in addition to setting their selected property. This will speed up iteration but will slightly reduce performance when selecting/deselecting items, as you'd have to then manipulate an array to add or remove them. If you're iterating lots and selecting/deselecting little (like I would expect) then this will be the best way to do it.

Hmm, it's tricky because I'm both iterating through LOTS and will be selecting/deselecting OFTEN. I'm also iterating selected in different places, multiple times, so I'm leaning towards putting them into their own array (and suffering the slight performance loss when selecting/deselecting).  

Link to comment
Share on other sites

 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...