Question

I am fetching a collection of items from a list using a CAML query. The returned items are then populated in my custom HMTL table. There is, however, another HTML table for which I need the same collection of items, but sorted differently.

Is there any way to get the same items collection sorted differently without having to execute another query over the same list?

I am required to use JSOM, so C# LINQ and such won't work for me.

Was it helpful?

Solution

You could sort list items using array.sort function:

function getListItems(listTitle,success,error)
{
   var ctx = SP.ClientContext.get_current();
   var list = ctx.get_web().get_lists().getByTitle(listTitle);
   var items = list.getItems(SP.CamlQuery.createAllItemsQuery());
   ctx.load(items);
   ctx.executeQueryAsync(function() {
       success(items);
   },error);
}


//sort List Items By ID (DESC)
function itemComparer(x,y) {
    var key = 'ID';
  if (x.get_item(key) < y.get_item(key))
     return 1;
  if (x.get_item(key) > y.get_item(key))
    return -1;
  return 0;
}



getListItems('Tasks',
      function(items)
      {
           //sort list items 
           items.get_data().sort(itemComparer); //sort items by ID (DESC)
           items.get_data().forEach(function(item){
              console.log(item.get_item('ID')); 
           });

      },
      function(sender,args){
         console.log(args.get_message());
     });

How to measure time taken by a function to execute

var start = new Date().getTime();
items.get_data().sort(itemComparer); //sort items by title
var end = new Date().getTime();
var time = end - start;
console.log('Execution time: ' + time);

OTHER TIPS

You can use the Order By in CAML:

<OrderBy>
 <FieldRef Name = "ID" Ascending = "TRUE"/>
</OrderBy>
<Where>
   ...
</Where>

Could you use linq?:

SPList objRelationShipList;
SPListItemCollection objRelationShipListItems;
objRelationShipList = SPContext.Current.Web.Lists["ListName"];
objRelationShipListItems = objRelationShipList.Items;
List<SPListItem> results = (from SPListItem item in objRelationShipListItems           
                            orderby item.ID
                            select item).ToList();
foreach(SPListItem in results)
{
....
}

Ref: http://blog.techperspect.com/2011/05/sorting-splistitemcollection-using-linq.html

Licensed under: CC-BY-SA with attribution
Not affiliated with sharepoint.stackexchange
scroll top