Java For Loop - Insert element after every n element

I've had a look around but couldn't find anything applicable - this is in a vtl file, but it's the same syntax I think.

I want to insert something after every n elements, rather than replace the nth element of a for loop which I have done accidentally whilst trying to solve the problem. What would be the best way to approach this? There could be thousands of items to loop through.

My current code is:

for(var i = 0; i < data.results.length; i++) { if(i % 5 == 0){ //Show the nth element } else{ //Display each table result normally } } 
5

1 Answer

Just remove the else statement. "else" means that the code will only be executed when the if-code is not executed. But to insert something (with other words: execute both block) you need to execute the if-code and also execute the code that you always would.

Like:

for(var i = 0; i < data.results.length; i++) { if(i % 5 == 0){ //Show the nth element } //Display each table result normally } 
3

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

You Might Also Like