What strategies can I implement to restructure my 'view' code so that it showcases items organized by year?

I am looking to refactor a section of code to organize and display my items by year without having to duplicate the code for each individual year. So far, I have attempted to loop through an array of years but have not been successful.

Below is the code snippet that I am currently duplicating in a 'view' file (ejs template) for 8 different years:

<ul><h3>YEAR 2017:</h3>
 <% items.forEach(function(el){ %>
  <% if(el.date.substring(7, 11) == "2017"){ %>
   <li><%= el.date %>: 
   <% if(el.url){ %>
    <a href="<%= el.url %>" title="<%= el.title %>"><%= el.title %></a>,
   <% }else{ %> 
    <%= el.title %>,
   <% } %>
   <% if(el.by){ %>
    <%= el.type %>, <%= el.by %>
   <% }else{ %>
    <%= el.type %>
   <% } %>
   @ <%= el.location %></li>
  <% } %>
 <% }); %>
</ul>

Answer №1

It sounds like you're on the right path with your use of an ejs template and array. Consider restructuring how you pass items so that they are in an array of objects like this:

items = [{"year": 2016, "items": [item1,item2...]},{"year":2017, "items": [item1,item2..]}, ... ]

Then you can iterate through them as follows:

<% items.forEach(function(year){ %>
    <ul><h3>YEAR <%= year.year %>:</h3>
        <% year.items.forEach(function(el){ %>
        ...
        <% } %>
<% } %>

Answer №2

Perhaps it could be structured like this, translated to eje syntax:


let array = []

let arrayElement = items.map(function(el,index){
  return el.date.substring(7,11);
})
array.push(arrayElement)

for (let i=0; i<array.length; i++){
  items.map(function(element,index){
    if(el.date.substring(7,11) == array[i]){
      //display your element
    }
  })
}

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

Encountering a "Cannot GET" error when utilizing mongoose

Details of my router.js file: const express = require("express") const Note = require("../models/nodeModel") const router = express.Router() router.route("/notes").get((req, res) => { Note.find({ show_day: "2020-9-10" }) .then(foundNotes ...

Sending a POST request to Mailchimp via Express using React: A step-by-step guide

I'm currently working on a project where users can sign up for a new membership through a form in React and have their information added to the Mailchimp member list via my Express server. However, I've encountered a CORS error and am unsure if I ...

Conceal or reveal radio buttons according to information in a table

How can I dynamically add and remove values from a table based on radio button selections? My goal is to add the selected value to the table and hide it from the radio button list, and if the value is deleted from the table, I want to show it back in the r ...

"An issue arises with AngularJS POST requests failing to return responses in the presence of active user

Currently, I am facing an issue with a POST request in Angular interacting with an API that returns a JSON object. Initially, everything was functioning smoothly until I integrated express.sessions into the process. The peculiar thing is that now, although ...

pre-iframe loading function

Is it possible to capture the state of an iframe while data is loading? The onload event only fires once all content has finished loading. I would appreciate any assistance with this issue. Thank you. ...

Express/axios fails to properly configure cookies and headers for response delivery

I am facing a complex issue with my project that involves two APIs. One API serves as the front-end of the application, while the other is for the back-end. The process simply entails sending requests from the front-end API to the back-end API. The front- ...

A step-by-step guide on initializing and setting a cookie value with expiration

Below is the code I have added. Can someone please help me locate the bug? Here is the code snippet: $_SESSION['browser'] = session_id(); setcookie($expire, $_SESSION['browser'], time() + (60 * 1000), "/"); echo "Value is: " . $_COO ...

Encountering a problem when attempting to use the 'express' module

After installing the Express framework globally, I encountered an error when trying to use it in my app. The error message is indicating that the module cannot be found. ...

What is the best way to create shapes in Three.js using the mouse?

I'm searching for a way to enable users to draw their own cube, similar to the example here (try drawing a cube on a grid): Screenshot: Shapesmith has efficiently solved this using Three.js, but it relies on Backbone.js. I'm wondering if it&apo ...

Challenges encountered while using Selenium WebDriver to upload images

I'm having trouble adding an image as a normal attachment to an email (not as an inline image). When inspecting the HTML DOM with Firebug, I noticed there are two elements with xpath //input@type='file', which is due to the presence of two b ...

Safari's Web Audio API suffering from subpar performance and various shortcomings

For my University project, I am developing an HTML and JavaScript-based mp3 player using the Web Audio API. You can check out the progress of this project by visiting this link: While everything is running smoothly on Firefox and Chrome, Safari is posing ...

Using JQuery to search for and remove the id number that has been clicked from a specific value

I am in need of assistance with deleting the clicked id number from an input value using jQuery. I am unsure of how to proceed with this task and would appreciate some guidance. To simplify my request, let me explain what I am trying to accomplish. Take ...

Error in Mongoose Schema Configuration Detected in NestJS App

I'm currently developing an e-commerce application using NestJS and MongoDB with Mongoose. I've been facing an issue while trying to implement a user's shopping cart in the application. The error message I keep encountering is as follows: ...

Guide to retrieving SQL data using Node.js with mysql2

I've decided to convert my code from Python to Node.js, and I'm encountering a problem when trying to retrieve data from SQL. In Python, it's simple to get the data, return it, and then use it in the code. Here is the Python code: def sql_g ...

Having trouble setting up jQuery UI Datepicker in my system

I am attempting to add a datepicker to my website, but it is not showing up in the browser. Could there be an issue with some of the other script files I have? Below is where my datepicker div is located: <body> <!-- Preloader --> <div id= ...

Remove checked rows in a table with a single click

I have created a table with a list and checkboxes next to each element. There is also a Delete button that I want to connect to the delete operation. Here is the code for the Delete button: <tr id="deleteproject" > <td wi ...

Analyzing an HTTP response containing a Content-Type header specifying image/jpeg

Currently, I am developing my first web application and the task at hand involves loading an image from a database and sending it to the client for display. On the server side, I have the following code: res.setHeader('Content-Type', pic.mimetyp ...

Utilizing a button's "data-" attribute to trigger a specific JavaScript function

I am trying to assign data to my buttons in a way that makes it accessible when clicked. While I can easily use JSON in a button's data attribute with a string as the key value, I am struggling to set the values to be a function instead. What I want ...

Enhancing search results with data retrieved from a jSON response

At the moment, I am using a logic to generate a list of titles. Now, I would like to include data from the response along with the code for each title in the list. const title = responseData.map(item => { return { label: item.title, val ...

Add a new component in front of another component based on its attribute value

Creating a dynamic DIV and positioning it in between other Div's based on their attribute value is the goal. The desired outcome is to maintain sequence. <div data-door="1">1</div> <div data-door="3">3</div> <div data-door ...