Reputation: 2191
I'm looping through a list of names, and want to check if any match a particular name eg "Todd".
If there's a match, I now want to loop through all the names again checking for the existence of Todd (1).
If there's a match, I now want to loop through all the names again checking for the existence of Todd (2).
And so on until I end up with the first available increment of the name eg "Todd (7)"
Is the idea to break the loop on a match, increment eg var count:int by 1, and restart the loop searching again, like...
if(names[i]=="Todd (" + count + ")" ...
?
If so, how do I restart a loop after breaking it once a conditional is met please?
Thank you.
Upvotes: 1
Views: 68
Reputation: 7316
There is an Array.indexOf(...) method that returns -1 if there are no matches or an index (0 or above) of the first exact match. So, something like that:
function availableIndex(list:Array, value:String):int
{
var result:int = 0;
var aName:String;
do
{
// Get the next index (starts with 1).
result++;
// Construct the next name based on the index.
aName = value + " (" + result + ")";
}
while (list.indexOf(aName) > -1);
// Proceed looping if such a name is in the given Array.
return result;
}
Upvotes: 1
Reputation: 75
Here is what I came up with:
you need a for loop first of all which will look something like this:
for(var i:int = 0; i < names.length - 1;i++){
if(names[i] == "Todd (" + count + ")"{
count++;
i = names.length - 1;
}
}
Let me know if you need the syntax for creating a function to hold this. That is if you want to call the function from another function, and in this case, I think the "count" variable would have to be global so that you don't call it from the function that modifies it, therefore, resetting it and not allowing what you want to happen, happen.
Another thing I wonder is if you are just meaning to organize an array then there are built-in sort functions that can do that.
Also, the i=names.length is really the only way I have come up with to stop the loop so far. I don't know if there's a better way, but this is what I know works at the moment. It may take some messing around with to get it right though.
Upvotes: 1