Quantcast
Channel: JavaScript – Xomino
Viewing all articles
Browse latest Browse all 34

Sorting an unsorted XPages document collection based on a date field

$
0
0

In one of my recent applications I had a requirement to return the top 500 search results, but sort them by a specific date field on the document, in descending order. Due to the size of the database doing a view.FTSearchSorted was not feasible as it was too slow. So I searched around and found some code for sorting a JavaScript Array of objects.

Creating the array

Search the database and push the search results into a JavaScript array

var sSearch = "[FIELD Subject contains smith]"
var dc:NotesDocumentCollection = db.FTSearch(sSearch, 500)
var doc:NotesDocument = dc.getFirstDocument();
var myArray=[]
var i=0
var sTemp = ""
while (doc != null) {
	i=i+1
	var obj={}
	obj.count=i
	obj.Customer = doc.getItemValue('Customer')
	obj.malfunctionEnd = @Text(doc.getItemValue('dateField'))
	obj.unid = doc.getUniversalID()
	myArray.push(obj)
	var tmpdoc = dc.getNextDocument();
	doc.recycle();
	doc = tmpdoc;
}

The sort function

Create a function to return a bubble sort of dates. This function works by comparing if two dates should be sorted based on their “getTime()” which returns a value in seconds.

function custom_sort(a, b) {
var ndtA:NotesDateTime = session.createDateTime(a.dateField);
var ndtB:NotesDateTime = session.createDateTime(b.dateField);

return ndtB.toJavaDate().getTime() - ndtA.toJavaDate().getTime()
}

The final step

Using the JavaScript sort function we can pass in the name of a callback function which adds additional processing to the sort function. The resulting array can then be processed by a repeat control providing the information out to the end user. All the code shown here would be placed in the value parameter of the repeat control.

myArray.sort(custom_sort);
return myArray


Viewing all articles
Browse latest Browse all 34

Trending Articles