You have to use setNextRequest(‘null’) to end the loop, otherwise Postman will run the next request in the collection which is why you are getting one more execution than expected (with undefined data).
The way I would do this rather than checking for undefined or null is to check the array length in the two put requests.
You retrieve the array from the collection variable and if the length is more than zero, then you continue to loop.
For example…
if (ids.length > 0){
postman.setNextRequest("getRequest");
} else {
postman.setNextRequest(null);
}