3

I want to retrieve subsites from current site collection. And it should be order by last item modified date.

I am able to retrieve subsites by following code :

channel_context = SP.ClientContext.get_current();
channel_web = channel_context.get_web();
channel_context.load(channel_web);

webCollection = channel_web.getSubwebsForCurrentUser(null);
channel_context.load(webCollection)
channel_context.executeQueryAsync(function(){
var temp = ""; 
var webEnumarator = webCollection.getEnumerator();
var i = 0;
while(webEnumarator.moveNext()){
   var curWeb = webEnumarator.get_current();
   temp = temp+"<br/>"+curWeb.get_title();
   webArray[i] = curWeb.get_title();
   i++;
}
document.getElementById("sliderDiv").innerHTML = temp;
}, onSliderImageLoadFailed);

But the webs which I am getting are sort by its title. Which I want to sort by Last Item Modified Date.
Is there any other option for sorting?
Do I have to manually apply some logic for sorting?

1
  • If you use the REST API you can do the get and the order by in one call. /_api/Web/Webs?$orderby=LastItemModifiedData Feb 20, 2015 at 16:12

1 Answer 1

3

The following example demonstrates how to return web sites sorted by last modified date:

function getWebs(success,error) 
{
    var ctx = SP.ClientContext.get_current();
    var web = ctx.get_web();
    var webs = web.getSubwebsForCurrentUser(null);
    ctx.load(webs);
    ctx.executeQueryAsync(
        function(){
            var result = [];
            for(var i = 0;i < webs.get_count();i++) {
               var web = webs.get_item(i);
               result.push(web);
            }
            result.sort(compareByLastModifiedDate);
            success(result);
        },
        error);
}

//sorting function with modifications from answer http://stackoverflow.com/a/1129270/1375553
function compareByLastModifiedDate(a,b) {
  if (a.get_lastItemModifiedDate() < b.get_lastItemModifiedDate())
     return -1;
  if (a.get_lastItemModifiedDate() > b.get_lastItemModifiedDate())
    return 1;
  return 0;
}

Usage

getWebs(function(webs){
    for(var i = 0;i < webs.length;i++){
        console.log(webs[i].get_lastItemModifiedDate());
    }
},
function(sender,args){
    console.log(args.get_message());
});

Key points:

2
  • Nice. PS: Instead of the webs.get_count loop, you could have done: var result = webs.get_data(); Feb 23, 2015 at 9:51
  • Indeed, it's more elegant way of getting an array of objects. Thanks Anders! Feb 23, 2015 at 10:10

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.