Search code examples
javascriptjqueryprototypejs

Port small function from jQuery to Prototype?


For once I need to use Prototype instead of jQuery, which I'm not very comfortable with. Can someone help me convert this following script:

var output={};
$('ul li').each(function(i,v){
    var l=$(this).text().substring(0,1).toUpperCase();
    if(typeof(output[l])=="undefined") output[l]=[];
    output[l].push($(this).text());
});
$('ul').empty();
for(var i in output){
    $('ul').append('<li><p>'+i+'</p></li>');
    for(var j in output[i]){
        $('ul').append('<li>'+output[i][j]+'</li>');
    }
}

Full source: http://jsfiddle.net/flxfxp/3LwH8/7/

Many thanks!


Solution

  • var output = $H({});
    
    $$("ul li").each(function(el){
      var l = el.innerHTML.substr(0,1).toUpperCase();
      if(typeof(output.get(l))=="undefined") output.set(l, []);
      output.get(l).push(el.innerHTML);
    })
    
    $$('ul').invoke("update", '');
    
    output.keys().each(function(key){
      var values = output.get(key);
      $$('ul').first().insert('<li><p>'+key+'</p></li>');
      values.each(function(v){
        $$('ul').first().insert('<li>'+v+'</li>');
      });
    });
    

    Tested with latest Prototype