Say I have some HTML elements:
<div>First</div>
<div>Second</div>
<div>Third</div>
Whose content I select via a:
$('div').text();
How can I make a “foldl” operation on the elements (iterate, accumulating a result), for example to join them using a newline?
$('div').text().foldl('', function(){ ... join_or_whatever ... })
According to the Wikipedia article on folding, JavaScript’s Array.reduce() (for foldl) and Array.reduceRight() (for foldr) functions provide array folding.
So your specific task becomes:
Note that not all implementations of JavaScript support reduce and reduceRight, so see this example implementation if needed.
UPDATED: Since jQuery doesn’t return a true array for $(selector) and some platforms do not support reduce and reduceRight on jQuery’s “array-like” collection, I’ve updated the answer to use $.makeArray() as suggested below. Thanks to @royas for the catch.