What is the method for invoking forEach within an addEventListener function?

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}`);
});

Answer №1

To display the list of students sorted by grade when clicking on the button #showStudents in the element #demo, you need to attach a listener as shown below:

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);
showStudents.addEventListener('click', () => {
  studentsOrder.innerHTML = ''
  students.forEach(e => studentsOrder.innerHTML += `${e.name} ${e.grade} <br />`);
})
<button id="showStudents">Show Students</button>

<div id="demo"></div>


You can also achieve the same result using the reduce() method with a concise one-liner solution:

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);
showStudents.addEventListener('click', () => studentsOrder.innerHTML = students.reduce((accumulator, student) => `${accumulator} <br /> ${student.name} ${student.grade}`, ''))
<button id="showStudents">Show Students</button>

<div id="demo"></div>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Chrome extension causing delays in rendering HTML on webpage

Currently, I am developing a script (extension) that targets a specific HTML tag and performs certain actions on it. The challenge I am facing is that this particular HTML tag gets dynamically loaded onto the page at a certain point in time, and I need to ...

What is the best way to incorporate options using jQuery?

Currently, I am incorporating a jQuery plugin for modals into my website. The plugin/code offers the functionality to customize the background color of the modal. For more details on how to do this, you can visit the plugin's official website. Althou ...

Invoke a JavaScript function with arguments upon clicking on a hyperlink

Struggling to generate code for an href tag with a JavaScript function that takes parameters - a string and an object converted into a json string. My initial attempt looked like this: return '<a style="text-decoration:underline;cursor:pointer" ta ...

Having trouble with submitting the code - need help resolving the issue

I'm facing an issue with my submit cancel code. The JavaScript code I implemented for preventing the submission function on my page isn't working as expected. While it does work to a certain extent, it's not fully functional. I am seeking a ...

AngularJS: Automatically refreshing ng-repeat based on checkbox filter updates in code

I have a container that is populated using ng-repeat="item in items | filter:isselected(item)". To filter the items, I have checkboxes with ng-model="selecteditem[$index]" and a filter function $scope.selectedItems = []; $scope.isselected = function(item ...

How can I modify this section of the code in Google Script to retrieve all columns?

My question is, how can I modify this code to fetch all columns from the array instead of just [0,1,2,3] Here is the line of code in question: const new_table = [0,1,2,3].map(x => make_row_from_col(this_table, x)).join('\n'); Using obje ...

"Triggering a JavaScript event when pasting text on

How can I capture a paste event on an iPhone using JavaScript and jQuery? I've already tried using jQuery's keyup and paste methods without success. Any suggestions? Here is the code I have attempted: $("#MyInputFields input").eq(0).b ...

Integration of Django, Angular, and databases in web development

My django project utilizes postgresql. I am exploring the use of angular as a front-end on my html pages. What is the recommended method to integrate angular js controllers into the django project for interacting with django models and the database, specif ...

Identifying Users with Socket.io Socket Connection

I have written some code examples to identify connected users via socket.io. Now, I need to implement a code on the index page to communicate with these users. The following code demonstrates how to send a message to user[1] saying "Welcome" and to user[2 ...

Experiencing difficulty decoding JSON output on jquarymobile's HTML page when making an Ajax request

After developing screens for my Android application using PhoneGap and jQuery Mobile, I have included the necessary JavaScript and CSS files in my HTML page: <link rel="stylesheet" href="css/jquery.mobile-1.3.1.css" /> <script src="js/jquery-1. ...

Prevent textArea from reducing empty spaces

I am facing an issue with my TextEdit application set to Plain Text mode. When I copy and paste text from TextEdit into a textarea within an HTML form, the multiple spaces get shrunk. How can I prevent the textarea from altering the spacing in the text? T ...

Mastering the art of handling errors with Javascript Promises

Through thorough research and some assistance, I have managed to create and annotate code that I believe will enhance the comprehension of Javascript Promises for individuals. However, I encountered a puzzling issue when attempting to trigger an error by ...

Using jQuery to combine the values of text inputs and checkboxes into a single array or string

I need to combine three different types of items into a single comma-separated string or array, which I plan to use later in a URL. Is there a way to merge these three types of data together into one string or array? An existing POST string User input f ...

Refresh dynamically generated list item (produced through PHP) following ajax request

Displayed below is the HTML code, generated using a while loop in PHP to add list items after retrieving data from a database. PHP: echo ' <li> <div class="collapsible-header"> <div class = "left"> <div class = "is ...

Leaving a message on someone else's Facebook wall by sharing a link to a website

I've been trying to figure this out, but I honestly have no idea where to start. Twitter has a feature that allows a link to open a box where users can write a tweet and post it directly to their chosen feed: It's really simple, just changing t ...

AJAX is delivering a unique random hash instead of the expected text

I am in the process of developing a live notification script, and I have encountered an issue. Instead of receiving plain text from the external file, the script is returning a random hash... Here is the function responsible for fetching data from test.ph ...

How to conceal the bottom bar in JQuery Colorbox iframe

I have implemented colorbox to showcase an Iframe of the registration page on my website. Here is how it looks... https://i.sstatic.net/z1RGK.png Upon closer inspection, I noticed a white bar at the bottom of the Iframe where the close 'X' butt ...

What are the steps to assign a variable by selecting a link from a list that is automatically generated?

After generating a list from a query, everything is working smoothly. Now, I want to use jQuery to trigger an event that will set a PHP variable for me. The scenario is simple - I have a table with 'column 1' and 'column 2'. Each link ...

"Dealing with duplicate values in an array when using ng-repeat in Angular

As I delve into the world of AngularJS, I find myself a bit perplexed by ng-repeat when working with arrays. Interestingly, the code below doesn't quite function as expected...but when I transform dayNames into an object with key-value pairs, it works ...

Retrieve embedded documents from MongoDB using PHP and store them in an array

I am facing a task where I have to retrieve all data from an embedded document in a MongoDB record and store it in an array using PHP variables. The structure of the mongodb record is as follows: { "_id" : ObjectId("987654321"), "roles" : ...