Loop through the array and print out only the last item

I am struggling to get my for loop to print out every item in the array, instead of just the last item. Can't seem to figure out where I'm going wrong:

var patients = ["Julia", "Kelly", "Thomas", "Clare"];

function lineOfPatients(line) {
 if (!line.length) {
     return "Empty"
 }
 var list = "";
 for(var i = 0; i < line.length; i++) {
     list += `${i + 1}. ${line[i]}, `
 }
 return `The line is currently: ${list}`
}

lineOfPatients(patients)

This code snippet returns "The line is currently: 4. Clare,"

My desired output should be "The line is currently: 1. Julia, 2. Kelly, 3. Thomas, 4. Clare"

Answer №1

If you have an array called patients, you can create a function in JavaScript to display the line of patients using the join method.

var patients = ["Julia", "Kelly", "Thomas", "Clare"];

function displayPatientLine(line) {
    if (!line.length) {
        return "No patients in line";
    }

    var lines = [];

    for(var i = 0; i < line.length; i++) {
        var patientName = `${i + 1}. ${line[i]}`
        lines.push(patientName)
    }

    return `The current line of patients is: ${lines.join(", ")}`;
}

console.log(displayPatientLine(patients));

Answer №2

The issue you're facing is the constant reassignment of the variable list within the loop, causing each iteration to overwrite the previous value.

To prevent this from happening, consider using the += operator instead of the = operator as shown below:

var patients = ["Alex", "Brianna", "Daniel", "Emma"];

function displayPatients(pList) {
 if (!pList.length) {
     return "The list is empty."
 }
 var queue = "";
 for(var j = 0; j < pList.length; j++) {
     queue += `${j + 1}. ${pList[j]}, `
 }
  return `Current patient lineup: ${queue}`
}

console.log(displayPatients(patients))

Answer №3

Your code is facing an issue where each time your for-loop iterates, it reinitializes the variable list = `${i + 1}. ${line[i]},`. This results in list only containing the last element from the array when you finally return.

An alternative approach could be:

function displayPatientLine(line) {
  if (!line.length) {
    return "Empty"
  }
  var resultString = "The current line of patients: "
  for(let i = 0; i < line.length; i++) {
    let patient = ` ${i + 1}. ${line[i]},`;
    resultString += patient;
  }
  return resultString;
}

Answer №4

Here is the solution you are looking for. (Got a bit carried away trying to make the code concise)

const patients = ["Julia", "Kelly", "Thomas", "Clare"]

const lineOfPatients = (line) => "The line currently consists of: " + (!line || !line.length) ? "Empty" : line.map((patient, idx) => `${idx + 1}. ${patient}`).join(', ')

console.log(lineOfPatients(patients))

The issue causing it not to work is that you are redefining the variable list inside every loop iteration. Even if you move it outside the loop, you are overwriting the output rather than appending to it within the for-loop. The final result will always be from the last iteration.

Answer №5

In order to optimize your code, it is recommended that you declare the variable list outside of the loop so that it is not recreated with a new value on each iteration. You can do this by initializing it as an array before the loop like this:

var list = new Array();

Then, within your loop, you can add elements to the array without recreating it every time like so:

list[i] = .....

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

Issue Encountered: Problem with Implementing Google Fonts in WordPress Theme

I am currently facing an issue with a function in my Wordpress theme's functions file that is supposed to add Google Fonts to the theme. However, I keep receiving the following error message: Parse error: syntax error, unexpected '=', expec ...

Node.js: The choice between returning the original Promise or creating a new Promise instance

Currently, I am in the process of refactoring a codebase that heavily relies on Promises. One approach I am considering is replacing the new Promise declaration with simply returning the initial Promise instead. However, I want to ensure that I am correctl ...

Using Vue.js to implement dynamic table rowspan functionality

Has anyone experimented with implementing dynamic table rowspan in vue.js? Here is the sample data { date: '2018-08-14', temp_que : 120, }, { date: '2018-08-14', temp_que : 120, }, { date: '2018-08-15', ...

Guide on duplicating a Select2 element integrated with Django and Python

I am facing an issue where the select element inside a div is not cloning correctly. The Select2 element does not retain the loaded values from the Django code when cloned. Is there a way to clone the div with all the Select2 element values intact? Current ...

Adjust the body class dynamically based on the URL in AngularJS

Here is the link to my website To Log In - http://localhost/ang/#/login To Access Dashboard - http://localhost/ang/#/dashboard See below for the HTML code for the body tag If the current URL is http://localhost/ang/#/login, then the body should include ...

Update values of Name, Longitude, and Latitude within the Google Maps API using JQuery

I am currently working on a feature for my website where a user can select a place from a list and have its Name, Longitude, and Latitude displayed on a map for easy identification. However, I am facing an issue with updating the values on the map when th ...

What is the proper way to input a Response object retrieved from a fetch request?

I am currently handling parallel requests for multiple fetches and I would like to define results as an array of response objects instead of just a general array of type any. However, I am uncertain about how to accomplish this. I attempted to research "ho ...

Can a middleware function in Node.js be executed asynchronously?

I've developed a middleware function to validate user access tokens (JWT) ... in case the JWT has expired, I automatically generate a new access token using the user's refresh token (if it is also valid). As my user base grows, I anticipate that ...

Apply various filters to extract and refine information from the database

I have successfully retrieved data from the database. The structure of the data is as follows: serie --- title (string) --- category (array) To filter the data, I have implemented a search filter using a computed property. This is how it looks: f ...

The loading bar animation doesn't begin at a blank slate

I'm currently working on a project that utilizes Django for the backend and Bootstrap for the frontend. I have to admit, I am quite inexperienced when it comes to front-end development; JavaScript seems like magic to me. One of the key features I nee ...

Tips on effectively transferring formarray to another component

I'm attempting to pass a formarray to a child component in order to display the values within the formarray there. Here is my current code, but I am struggling to figure out how to show the formarray values in the child component. app.component.html ...

How to implement loading an external script upon a page component being loaded in NextJS

I recently transferred an outdated website to Nextjs and I am having trouble getting the scripts to load consistently every time a page component is loaded. When navigating between pages using next/link component, the scripts only run the first time the ...

Events bound to JSX elements created in an array map are not being triggered by React

My current task involves working on a compact react + typescript (1.6) application designed for editing slideshows. The functionality of the app is straightforward. A sidebar on the left displays all existing slides, and upon clicking, a canvas appears on ...

Add the attribute's value to an array

$(document).ready(function() { function randomColor() { return 'rgb(' + Math.round(Math.random() * 255) + ', ' + Math.round(Math.random() * 255) + ', ' + Math.round(Math.random() * 255) + ')' ...

What is the meaning of the term writeHead?

Upon reviewing a GroupMe bot template in nodejs, I noticed a common occurrence of the function call res.writeHead(200);. What is the typical purpose of writeHead(200)? Is it a shorthand for "write header"? ...

Retrieve specific information from checkboxes within a form

I'm working on a form that includes multiple checkboxes populated with data from a JSON file using ng-repeat. After submitting the form, I need to retrieve the data from the checked checkboxes. How can I accomplish this in my controller after the form ...

How to update specific subelements in MongoDB using targeted queries

Here is an example of my database structure: { "_id" : ObjectId("51e66873f6a6600436000001") ,"email" : "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="dcbdafb89cbdafb8f2b8b9">[email protected]</a>", ,"attri ...

Transforming JavaScript date into JSON date structure

Currently, I am integrating an API that requires the JSON date format. My task involves converting a JavaScript date Sat Jan 17 1970 07:28:19 GMT+0100 (Romance Standard Time) into the JSON date format: /Date(1405699200)/ ...

Is it possible to automatically play a sound clip when the page loads?

Is there a way to automatically play a sound clip when my page loads? Are there any specific JavaScript or jQuery methods I can use for this, as I am developing my page using PHP. ...

Multer can handle the uploading of various files from multiple inputs within a single form

I've searched everywhere on the internet, but I can't seem to find a solution that matches my specific issue. As someone new to Node.JS, I'm attempting to upload two different pictures using Multer from the same form. Here's what my for ...