Apologies if this is a newbie question, Im learning JS and jQuery. I'm trying to sort an array of objects by the key first_name after a button click but Ive been unsuccessful.
I've tried grabbing a div with a class of ajaxStyling. Then insert adjacent html for the button with id of #btn-click. Then I use jQuery to hijack the click and try to sort with a function using newCourse.students (my array of objects/works when doing console.log) but the whole sort function is not working. Im not getting errors on the console but the text wont sort. Maybe is my return? or maybe is that i need to append again?
$('#btn-click').on('click', (e) => {
e.preventDefault()
// console.log(newCourse.students)
newCourse.students.sort(function(a, b) {
// return a.first_name > b.first_name;
var nameA = a.first_name.toUpperCase();
var nameB = b.first_name.toUpperCase();
if (nameA < nameB) {
return -1;
}
if (nameA > nameB) {
return 1;
}
return 0;
});
newCourse.students
})
What I get when I log newCourse.students
(3) [{…}, {…}, {…}]
0: {id: 11, first_name: "Stefan", last_name: "Candelaria", …}
1: {id: 12, first_name: "Robby", last_name: "Pasurin", …}
2: {id: 10, first_name: "Rafa", last_name: "Lopez", …}
length: 3
My html. Would like to sort by name after a button click to achieve the following order 1.Rafa Lopez 2.Robby Pasurin 3.Stefan Candelaria ...instead of the order below.
<div class="container">
<div class="ajaxStyling">
<a href="/courses/6" data-id="6"><h3 class="showText">Adobe Analytics 201 by Adam Greco</h3></a>
<p class="show_link">Stefan Candelaria</p>
<p class="show_link">Robby Pasurin</p>
<p class="show_link">Rafa Lopez</p>
</div>
<button id="btn-click">Click Me!</button>
</div>
newCourse.studentsdoes?newCourse.studentsis calling students which is an attribute of Course. I tried your reco but didnt work : (