Reputation: 3166
I'm building an array of objects and outputting them to HTML. Then, I'm running a sort on those objects to sort alphabetically by the courseTitle
property.
Something's not working properly though.
//variable declaration
var Learning = [
{
courseTitle: "Title B",
courseDesc: "description"
},
{
courseTitle: "Title A",
courseDesc: "description"
}
];
//array output to HTML
$.each(Learning, function (key, value) {
var item = value;
var newcontent =
`<ul>` +
`<li>` + item.courseTitle + `</li>` +
`<li>` + item.courseDesc + `</li>` +
`</ul>`
var html = $("#Learning").html();
$("#Learning").html(html+newcontent);
});
//sorts ascending a > b
Learning.sort(function(a, b){
if(a.courseTitle < b.courseTitle) { return -1; }
if(a.courseTitle > b.courseTitle) { return 1; }
return 0;
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="Learning"></div>
Upvotes: 0
Views: 34
Reputation: 8670
You're outputting to HTML before you sort. Altering the data itself does not reactively alter the DOM. Therefore you need to sort before appending to the DOM.
The following will work:
//variable declaration
var Learning = [
{
courseTitle: "Title B",
courseDesc: "description"
},
{
courseTitle: "Title A",
courseDesc: "description"
}
];
//sorts ascending a > b
Learning.sort(function(a, b){
if(a.courseTitle < b.courseTitle) { return -1; }
if(a.courseTitle > b.courseTitle) { return 1; }
return 0;
})
//array output to HTML
$.each(Learning, function (key, value) {
var item = value;
var newcontent =
`<ul>` +
`<li>` + item.courseTitle + `</li>` +
`<li>` + item.courseDesc + `</li>` +
`</ul>`
var html = $("#Learning").html();
$("#Learning").html(html+newcontent);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="Learning"></div>
Upvotes: 2
Reputation: 683
Sorting the contents of the original data array after already committing them to the DOM does not automatically update their sort order in the DOM. The DOM does not know that you have changed the original array, because it has no ties to the original array.
If you want your items sorted you have to do it before adding it to your html.
If you move the sort call to before the $.each, you will see that it sorts them correctly.
Upvotes: 1