Skip to content

Instantly share code, notes, and snippets.

@nicksheffield
Last active December 28, 2015 15:38
Show Gist options
  • Save nicksheffield/7522808 to your computer and use it in GitHub Desktop.
Save nicksheffield/7522808 to your computer and use it in GitHub Desktop.
Push a string into an array. If there is already an instance of the string in the array, append an appropriate number to the end of the string first.
function append(arr, string){
// if the string does exist in the array ..
if(arr.indexOf(string) != -1){
var n = 2;
var fin = false;
// .. loop indefinitely until we decide we have found a usable number.
while(!fin){
// if the string + the number doesn't exist
if(arr.indexOf(string+' ('+n+')') == -1){
// add it
arr.push(string+' ('+n+')');
// and end the loop.
fin = true;
// if the string + number does exist, then increase n and repeat the loop
}else{
n += 1;
}
}
// if the string doesn't exist in the array ..
}else{
// ..add it
arr.push(string);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment