Check if array exist/ true or false

Hi guys, you may help me a lot. I am trying to write a script to process(merge color) files, if the array of those file names exist(hope I expressed myself clearly). I am not sure why the ture false didn’t work. Here is my script. Many thanks:

for (j = 0; j < list.length; j++) {
file = list[j];
filename = File.getNameWithoutExtension(list[j]);

	if(endsWith(file, "_1.tif")) {open(file); files_1 = Array.concat(files_1, list[j]);}
	else{continue;}
}
if( files_1 == false){merge(files_1);}
else{print("no array");}

Hi,
Your code can’t work as the function Array.concat returns an array rather than True/False. So, your variable ‘files_1’ is an array. You probably want to add a separate variable to keep track of whether or not you want to call your merge function.
Alternatively, it may work for you to check the length of the array ‘files_1’ to see whether you want to call the merge function.
Hope this helps,
Volko

Hi Volko, Thanks a lot. I checked the length of the array “files_1”, it worked.

if(endsWith(file, "_1.tif")) {open(file); files_1 = Array.concat(files_1, list[j]);}
	else{continue;}
}
if( files_1.length > 0){merge(files_1);}
else{print("no array");}

But if the array was not created, then the files_2.length will be an undefined variable.
if(endsWith(file, “_1.tif”)) {open(file); files_1 = Array.concat(files_1, list[j]);}
if(endsWith(file, “_2.tif”)) {open(file); files_2 = Array.concat(files_2, list[j]);} // the file with "_2.ti " does exist so no array is actually created.
else{continue;}
}
if( files_2.length > 0){merge(files_2);}
else{print(“no array”);}

Hi Volko,
thanks again. I think problem olved. I added one empty array at the beginning, then there always will be an array, the difference is whether the array is empty or not.

files _2 = newArray();

1 Like

Great! Alternatively, I would have suggested to create a variable at the start of your code to keep track of whether the array was created. Something like:

var array_1_created = FALSE

if(endsWith(file, "_1.tif")) {
   open(file); 
   files_1 = Array.concat(files_1, list[j]);
   array_1_created = TRUE;
}else{                     // I don't think you actually need the else{continue} part of the code
   continue;
};
if( array_1_created == TRUE){
   merge(files_1);
}else{
   print("no array");
};

1 Like

Hi Volko,
Perfect. It worked. And you are right the else {continue} code is redundant. Thanks a lot.