Easier method for displaying array elements as list items in JavaScript

Working on exercises from a manual that required printing array items into list elements.

Here is the code provided:

<!doctype html>
<html lang="en>

<head>
  <title>Temperatures</title>
  <meta charset="utf-8">
  <script>
    function showTemps() {
      var tempByHour = new Array();
      tempByHour[0] = 59.2;
      tempByHour[1] = 60.1;
      tempByHour[2] = 63;
      tempByHour[3] = 65;
      tempByHour[4] = 62;
      for (var i = 0; i < tempByHour.length; i++) {
        var theTemp = tempByHour[i];
        var id = "temp" + i;
        var li = document.getElementById(id);
        if (i == 0) {
          li.innerHTML = "The temperature at noon was " + theTemp;
        } else {
          li.innerHTML = "The temperature at " + [i] + " was " + theTemp;
        }
      }
    }
    window.onload = showTemps;
  </script>
</head>

<body>
  <h1>Temperatures</h1>
  <ul>
    <li id="temp0"></li>
    <li id="temp1"></li>
    <li id="temp2"></li>
    <li id="temp3"></li>
    <li id="temp4"></li>
  </ul>
</body>

</html>

I initially attempted to create my own solution using a for loop and the createElement method, but unfortunately it did not work as expected.

var messageGen = function() {
var forecastByHour = [32, 15, 19, 25, 21];


for (var i =0; i <= forecastByHour.length; i++) {
  var temp = forecastByHour[i];
  var message = "On the " + [i] + " hour the expected forecast is" + temp;
  var listItems = document.createElement("li");

    listItems.innerHTML = message
}

}

Does anyone have an easier solution for this task?

Answer №1

If you want to efficiently create HTML and manipulate your temperature data, consider using advanced Array manipulation functions such as map and join. This approach can be much easier to understand compared to other solutions once you grasp the higher-level methods involved (refer to the linked MDN documentation pages).

function displayTemperatures() {
  var temperatures = [59.2, 60.1, 63, 65, 62].map(function (t, i) {
    return 'The temperature at ' + (i || 'noon') + ' was ' + t
  })

  document.getElementById('temperatures').innerHTML =
    '<li>' + temperatures.join('</li><li>') + '</li>'
}

displayTemperatures()
<h1>Temperature Readings</h1>
<ul id="temperatures"></ul>

Answer №2

Here is my approach to solving this particular problem:

  1. Start by creating an array containing the necessary data.
  2. Next, develop a function that generates an li element based on given parameters.
  3. Utilize a for loop to add the generated li element as a child to the designated ul element.

var tempByHour = [ 59.2, 60.1, 63, 65, 62 ];

function createLi(temp, i) {
    var li = document.createElement("LI");
    
    if (i === 0) {
        li.innerText = "The temperature at noon was " + temp;
    } else {
        li.innerText = "The temperature at " + i + "was " + temp;
    }
    
    return li;
}

var i,
    len = tempByHour.length,
    target = document.getElementById("temps");

for (i = 0; i < len; i++) {
    target.appendChild(createLi(tempByHour[i], i));
}
<h1>Temperatures</h1>
<ul id="temps"></ul>

I prefer utilizing for loops over maps or forEach loops. Performance benchmarks show that for loops are approximately 60% faster than maps and about 80% faster than forEach loops.

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

The Angular.copy() function selectively copies properties and does not duplicate everything

Exploring a function within a service: $scope.addPeriod = function(newPeriod) { if(newPeriod.from !== '' && newPeriod.until !== '') { var index = $scope.newPeriods.indexOf(newPeriod); ...

Having difficulty accessing information from the parent scope

As I continue to dive into AngularJS, I've encountered some challenges with scopes in my current project. Here is my controller and directive setup: angular.module('myModule', []) .controller('myController', ['$scope', ...

Avoiding HTML/JavaScript escape: Injecting database field content into DOM using jQuery

My goal is to integrate HTML and JavaScript code stored in a textfield of my database into my Rails application. The code looks like this: <script type="text/javascript"> document.write('<div id="test"></div>'); </script&g ...

What is the best way to access the value of a child element using $event within AngularJS?

Utilizing $event.currentTarget to access the element on ng-click: <div ng-click="eventHandler($event)" class="bg-master m-b-10" id="slider-tooltips" nouislider=""></div> Upon inspecting my controller&apo ...

Increase the date by one day in the minimum date field using the date picker

I've been struggling with adding one day to the minDate in my code. Despite trying multiple solutions from Stackoverflow, none of them have worked successfully. Here is the code I currently have: $('#cal_mulamhn').datepicker({ minDate ...

Steps for including a Google Doc hyperlink within a current script

I recently came across a useful template script for creating an automated help desk workflow. Once a user fills out the form, they receive an email with a message saying "Thanks for submitting your issue. \n\nWe'll start working on it as soo ...

Firefox is mistakenly interpreting a pasted image from the clipboard as a string instead of a file, causing

I am facing an issue where I am attempting to extract images from a contenteditable div using the paste event. The code works perfectly in Chrome but does not function as expected in Firefox. I have implemented the following code: $(window).on("paste& ...

Implementation of Vue.js for filtering search results in a list view

I would like to enhance my searching functionality by including both header and content. Currently, the search is only based on content. Any recommendations on how to modify this source code to accomplish that? Thank you Below is the HTML snippet: <di ...

The useEffect hook is failing to trigger within the Higher Order Component (Hoc

My component was working fine without using a HOC, but now that I've wrapped it inside withSpinner HOC, the fetching process does not start. const CollectionPage = (props) => { const { isCollectionLoaded, isCollectionFetching } = props; useEf ...

Searching Firebase by using comparison operators on various fields

const FindFiis = async () => { const data: any[] = []; // Firebase query with inequalities on different fields to retrieve docs. // Objective: Select documents where dividendYield is between 8 and 20 and pvp is less than or equal to 1. ...

"Step-by-step guide on adding and deleting a div element with a double click

$(".sd").dblclick(function() { $(this).parent().remove(); }); <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <table width="750" border="0" cellpadding="0" cellspacing="0"> <tr> <t ...

Error: The function $(...) that is being called is not recognized as a dialog function

My website has been giving me headaches as I try to integrate a basic CMS. Despite three full days of work, I am still facing one persistent problem! I have exhausted all my known methods, researched some solutions, but none seem to work. In order to iden ...

Browsing Identical Groups of Multiple Selection Drop Downs Using Javascript

Is there a way to loop through multiple form elements iteratively in order to identify the selected items from a select multiple input? I am looking for a solution that allows me to determine which selection box is being operated on and then extract all t ...

Exploring the possibilities of Three.JS by manipulating the world position of a child 3D object

I have a child object3D that is part of a group Object3D. While the child object's position is displayed relative to the parent object's space, I am trying to change the location of the child object within the 3D space. To do this, I first need t ...

Displaying Dates in an Express Application using EJS

I have a MySQL table with a column containing date data. I am building a webpage to display this data in a more user-friendly way. Currently, the displayed result looks like this: https://i.sstatic.net/lGamr.png I would like the dates in the column to ...

What is the preferred method for logging out: using window.location.replace('/') or setting window.location.href to window.location.origin?

When it comes to a logout button, which is the better option: window.location.replace('/') or window.location.href=window.location.origin? Can you explain the difference between these two methods? It's my understanding that both of them remo ...

Exploring an object to find the value of an array

Here is the object that I am working with: var list = { nums: [ [117], [108] ], numsset: [ [2256, 2265], [234], [3445, 3442] ] }; Imagine there is an input field on the page where a user can type a number. How can I search the ...

My requests are failing because jQuery AJAX does not send hashtag symbols

There's a challenge I'm facing while working with Elixir Phoenix and React.JS. The Token I have includes hashtags, and when I send a request to verify it, the hash symbols and everything after them are not being sent, causing the request to fail. ...

Organize cells with multiple lines containing date values in Google Sheets by arranging them in descending order

Within a collaborative spreadsheet containing multiple lines in one cell, I am attempting to showcase the formula result organized by date in descending order (starting with the most recent year like 2022, followed by 2021, and so on) within each individua ...

Displaying a plethora of data points on a single graph using jQchart with a

I'm currently using jQchart to showcase a graph, but I'm running into an issue with the title property only displaying a single line of text. The current title being displayed on the graph is as follows: text: chartTypeText + ': ' + ch ...