javascriptjqueryjquery-1.5

How can I group a collection of elements by their adjacency?


Let's say I have a list that looks like this:

<ul>
    <li id="q"></li>
    <li id="w"></li>
    <li id="e"></li>
    <li id="r"></li>
    <li id="t"></li>
    <li id="y"></li>
    <li id="u"></li>
    <li id="i"></li>
    <li id="o"></li>
</ul>

I need to do something like this:

function get_important_elements() {
    // completely contrived;
    // elements are guaranteed to be contained within same ul
    // but nothing else unique in common (class, attrs, etc)
    return $('#q, #w, #r, #u, #i, #o');
}

function group_adjacent($elems) {
    return $elems; //:(    
}

$(function () {
    var $filtered_list = get_important_elements();

    var groups = group_adjacent($filtered_list);

    // groups should be 
    // (shown by ID here, should contained actual elements contained
    // within jQuery objects): 
    // [$([q, w]), $([r]), $([u, i, o])]
});

How could I go about this?

Note that the IDs and classes used in the list are 100% contrived. In the real code upon which I'm basing this, I have a collection of li elements that are a subset of the lis contained in a single ul. This subset was determined by their contents, which are not important to the question at hand, not by class. They only share a class in the example for ease of getting my point across.


Solution

  • function group_adjacent($elems) {
        var rArr = [],
            currArr = $([]);
        $elems.each(function() {
            var $this = $(this);
            currArr = currArr.add($this);
            if (!$elems.filter($this.next()).length) {
                rArr.push(currArr);
                currArr = $([]);
            }
        });
        return rArr;
    }
    

    http://jsfiddle.net/adamjford/5q8fZ/3/