Reputation: 43
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">
$.ajax({
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>");
count++;
});
},
error: function (error) {
alert(JSON.stringify(error));
}
});
</script>
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.
Upvotes: 0
Views: 43
Reputation: 155250
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 ) {
data.d.results.sort(
function( left, right ) {
return left.Title.localeCompare( right.Title, { sensitivity: "base" } );
}
);
// rest of your code here
}
Upvotes: 2