pranay godha
pranay godha

Reputation: 655

Sort and separate a set of list elements using JavaScript/jQuery

I have a question Sort the list (you can use default JS/jquery sorting functions ) Break the sorted list apart into different sub-lists with a maximum of 'x' items each, 'x' being a parameter you pass in. The above sample result assumes x=2

<ul>
   <li> 4 </li>
   <li> 1 </li>
   <li> 7 </li>
   <li> 5 </li>
   <li> 3 </li>
 </ul>

Write a function to convert that to

<ul>
    <li> 1 </li>
    <li> 3 </li>
</ul>
 <ul>
    <li> 4 </li>
    <li> 5 </li>
</ul>
<ul>
    <li> 7 </li>
</ul>

Feel free to use any libraries/references you like within reason (i.e., don't use a library which has a "splitList" function). The key is to do this as efficiently as possible in terms of DOM manipulation.

i solved this question by creating separate list and deleted the original but I am wondering how can we do it by only modifying the existing one.(I mean modify on the fly while traversing)

Upvotes: 4

Views: 1623

Answers (5)

Andy E
Andy E

Reputation: 344665

This partially uses an answer I wrote before that divides elements into groups, with the addition of sorting them first:

Working demo: http://jsfiddle.net/AndyE/QVRRn/ 
var i   = 0,
    ul  = $("ul"), 
    lis = ul.children().detach(),
    group;

// Sort the elements
lis.sort(function (a, b) {
    return $.text(a).localeCompare($.text(b));
});

// Wrap the elements
while ((group = lis.slice(i, i += 2)).length)
    group.wrapAll('<ul></ul>');

// Replace the original UL element
ul.replaceWith(lis.closest("ul"));

It's important to detach the <li> elements from the document before manipulating them, this will make the operation much faster on large sets.

Upvotes: 1

Frias
Frias

Reputation: 11291

If you must have to manipulate DOM, I believe your question was answered. But...

DOM manipulation is slow. Concatenate strings also.

The sort function was taken from here: How may I sort a list alphabetically using jQuery?

Live demo: http://jsfiddle.net/gknjQ/1/

Upvotes: 0

Rob W
Rob W

Reputation: 349102

The most efficient method to sort is by using the native Array.sort method (jQuery().sort implements the Array.sort). Fiddle: http://jsfiddle.net/RJEJQ/1/.

The code can become even more efficient by getting rid of jQuery, and using document.createElement() and ordinary for() loops.

var originalUl = $('ul');
var listElements = originalUl.children('li'); //List
listElements.sort(function(x, y){
    return parseInt(x.textContent, 10) - parseInt(y.textContent);
});
//Sorted by number, 1, 2, 3, ...

var newList = $(""); //Placeholder
listElements.each(function(i){
    if(i%2 == 0){ //If even, a new list has to be created
        originalUl.before(newList);
        newList = $("<ul>"); //Create new list

    }
    newList.append(this);
});
if(newList.length) { // If there are any remaining list elements in the holder.
    originalUl.before(newList);
}
originalUl.remove(); //Remove original, empty ul.

As seen at this demo, the result looks like:

ul
    li 1
    li 3
ul
    li 4
    li 5
ul
    li 7

Upvotes: 1

run
run

Reputation: 1186

var optionTexts = [];
        $("ul li").each(function() { optionTexts.push($(this).text()) });
        optionTexts.sort();
        //alert(optionTexts.length);
        var splityby = 2;//change this value how you want to split
        var itmes= parseInt(optionTexts.length/splityby);
        var remaining = optionTexts.length%splityby;
        //alert(itmes+'and'+remaining);
        var st='';
        var i=0;
        for(k=0;k<itmes+remaining;k++){
            st+='<ul>';
            for(j=0;j<splityby;j++){
                if(i<optionTexts.length){
                st+='<li>'+optionTexts[i++] +'</li>' ;
                }
            } 
            st+='</ul>';
        }
        $('#hi').append(st);

html

    <div id="hi"></div> 
<ul>    <li> 4 </li>    <li> 1 </li>    <li> 7 </li>    <li> 5 </li>    <li> 3 </li>  </ul>

Upvotes: 1

FoRever_Zambia
FoRever_Zambia

Reputation: 1169

html first:

<ul id="list">
   <li> 4 </li>
   <li> 1 </li>
   <li> 7 </li>
   <li> 5 </li>
   <li> 3 </li>
</ul>
<div id="container"></div>

javascript(jquery):

function sortText(a,b){  
    return $(a).text().trim() > $(b).text().trim() ? 1 : -1;  
};
var ul = $('#list');
var elements = ul.find('li').detach();
var i=2;
var lastul;
var container = $('#container');
elements.sort(sortText).each(function(index){
    if (index % i === 0) {
        container.append(lastul);
        lastul = $('<ul></ul>');
    }
    lastul.append(elements[index]);
})
container.append(lastul);
ul.remove();

Upvotes: 1

Related Questions