4

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)

0

5 Answers 5

1

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();
Sign up to request clarification or add additional context in comments.

Comments

1
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>

Comments

1

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

1 Comment

Note: Change i%2 by i%3 if you want to display three list items per <ul>.
1

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.

Comments

0

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/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.