JarrodOliver JarrodOliver - 3 months ago 21
Javascript Question

How would I sort list items that I am getting from a document library with javascript?

Currently I have some JavaScript that retrieves list items and displays them as part of an unordered list. I've been given the task of modifying the javascript below to sort items.

<script type="text/javascript" defer="defer">

url: "/NewsEvents/_api/web/lists/GetByTitle('Newsletters')/items?$select=Title,FileRef",
type: "GET",
headers: {
"accept": "application/json;odata=verbose",
success: function (data) {
returnedvalue = data;
var count = 0;
$.each(data.d.results, function (index, item) {
$('#NL ul').append("<li>" + "<a href='" + item.FileRef + "'>" + item.Title + "</a>" + "</li>");
error: function (error) {


I haven't done much javascript before and am willing to learn. Would love to be pointed in the right direction rather than just given an answer.

Dai Dai

I'm assuming that data.d.results is a JavaScript array that resembles the following example:

results: [
        Title: "Article Title",
        FileRef: "something/or/other"
        Title: "Another Article Title",
        FileRef: "something/or/other/again"

JavaScript's Array type has a built-in sort method, which accepts a custom comparator ( https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort ).

I use the localeCompare ( https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/localeCompare ) method to compare the Title values of each array element.

I specify sensitivity: "base" to perform a case and and accent invariant comparison, so "article" and "Article" are considered equal when compared.

success: function( data ) {

        function( left, right ) {
            return left.Title.localeCompare( right.Title, { sensitivity: "base" } );

    // rest of your code here