How to do foldl for values ​​returned by a selector in jQuery?

Say I have some HTML elements:

<div>First</div>
<div>Second</div>
<div>Third</div>

Whose content I select through:

$('div').text();

How can I do the “foldl” operation for elements (iteration, accumulating the result), for example, to join them using a new line?

$('div').text().foldl('', function(){ ... join_or_whatever ... })
+3
source share
3 answers

According to the Wikipedia article on folding , JavaScript Array.reduce () (for foldl) and Array.reduceRight () (for foldr) functions provide array drilling.

So your specific task:

var result = $.makeArray($('div')).reduce(function(prev,curr){ 
        return prev + '\n' + $(curr).text() 
});

, JavaScript Right, . , .

: jQuery $(), Right jQuery "array-like", $.makeArray() . @royas .

+5

, foldl,

, :

var newArray = [];
//'div' is an outer container of your inner divs
$('div').each(function(index, Element) {
    newArray.push($(this).text());
});

$('body').append(newArray.join(''));
+1

I think I understand what you mean by the word "foldl", not sure ... But try the following:

var finalStr = "";
$('div').each(function(index) {
   finalStr += $(this).text() + "<br>";
});

Available at: http://api.jquery.com/each/

0
source

All Articles