Fun with Loops: Accumulating Results for Items

This is just a quick hack for anyone looking to implement simple loops where previous context needs to be available for the next iteration. For the technical, it’s kinda like implementing a version of “Array.reduce()” but with a whole lot of extra steps! Why is this useful? Well, read on!
Note, there is a probably a better way to do so using the code node so if given the choice, you might want to consider that instead!

Exhibit 1. Colours of the Rainbow

A simple demonstration to show what I’m talking about. Every iteration of the loop can reference one or more previous iteration result.

Exhibit 2: Agent Kiwi

Ok, so no doubt the first exhibit has some of you raising confused eyebrows but hear me out. This technique really shines when you need start getting LLMs into the mix! Here’s a trivial example where the previous context helps prevent duplicate ouputs from the LLM.

Exhibit 3: Hemingway would be proud

It’s also a neat little trick for content generation! In some scenarios without previous context, partially generated output may struggle to fit together fluidly at the end. Rather than using external memory/storage or doing a rewrite, this could be a quick and dirty alternative instead.

That’s it!

Just a little hack I came across and thought it was pretty cool.

8 Likes

I love this Jim

1 Like

This is actually genius! Thank you for sharing Jim, you’re a legend!

1 Like

Hi, thanks for sharing! I’m new on n8n, i see it do loops also without loop node.

In case 3 we could have:

Set → Split Out → Ai agent → done.

What’s the difference to add a loop node vs dont use it?
Thanks in advance

Jim would be able to give more detailed answer but in the meantime: the difference is control. With a loop you choose how many inputs get processed. Also you can access outputs from previous rounds. With a split out node and AI agent, the agent handles each input as “standalone”.

1 Like