I am working with an array of objects containing names and grades of students. My task is to sort them in descending order, which I have achieved using the forEach method. However, I am struggling to figure out how to implement it within an addEventListener so that when a button is clicked, the names and grades of the students are displayed in the browser. In my HTML document, there is only one empty paragraph with an id of "#demo" and a button with an id of "#showStudents". The button is meant to populate the empty paragraph with the student names and grades upon being clicked. Below is the code snippet:
const studentsOrder = document.getElementById("demo");
const showStudents = document.getElementById("showStudents");
const students = [
{
name: "Michael",
grade: 9,
},
{
name: "Tom",
grade: 6,
},
{
name: "Lisa",
grade: 8,
},
{
name: "Ron",
grade: 5,
},
{
name: "Daniel",
grade: 3,
},
{
name: "John",
grade: 2,
},
{
name: "Louise",
grade: 7,
},
];
students.sort((a, b) => b.grade - a.grade);
students.forEach((e) => {
console.log(`${e.name} ${e.grade}`);
});