bucket_list

Description

Moves elements of a list into separate ‘buckets’ based on criteria.

 object bucket_list( list source , mixed bucketmethod )

Take a list and turn it into an object. Each field of the resulting object will contain a list of items within that “bucket”. This is especially useful if you have a feed of content and you want to break it up into different sections based on some criterion.

If bucketmethodis a string, it treats that as a field name to use as the bucket key.

If bucketmethodis a lambda, it evaluates that lambda and uses the result as a bucket key. If the lambda returns null, the item will not be included.

Examples

Supposing a data feed that looks like this:

{"content":[   
   {"url":"http://www.example.com/item-1","section":"sidebar","tags":["furniture","wood"],   
   {"url":"http://www.example.com/item-2","section":"sidebar","tags":["furniture","metal"],   
   {"url":"http://www.example.com/item-3","section":"main","tags":["art","wood"],   
  {"url":"http://www.example.com/item-4","section":"main","tags":["art","metal"], ]}

Break into buckets based on section:

{sections = bucket_list(content, 'section')} 
{foreach sections.main as content} ... item-3 and item-4 appear here {/foreach} 
{foreach sections.sidebar as content} ... item-1 and item-2 appear here {/foreach}

Break into buckets based on tag membership:

{sections = bucket_list(content, lambda x: contains(x.tags,'metal') ? 'metal' : 'nonmetal')} 
{foreach sections.metal as content} ... item-2 and item-4 appear here 
{/foreach} 
{foreach sections.nonmetal as content} ... item-1 and item-3 appear here 
{/foreach}
Top