Exploring the interplay between loops and variables in Express/doT.js to effectively display MySQL query results

Within my Express route, I am retrieving a collection of entries from a MySQL database. These entries consist of words and associated line numbers that require the printing of all words on the same line together with a line break.

word  |  section
----------------
Lorem |     1    
ipsum |     1
dolor |     1
sit   |     2
amet  |     2

Utilizing doT.js as my templating engine, my objective is to display this data as follows:

Lorem ipsum dolor
sit amet

As I iterate through the array of results from MySQL, I aim to print out each word. However, I am currently struggling to compare the line number of the current index with that of the previous one. My initial thought is to establish a variable for the current line and compare it to the preceding line. If they differ, then I can introduce a <br> tag. Yet, I am encountering difficulties in implementing this solution.

Do I need to resort to using a helper method? If so, could someone direct me to a reliable tutorial? Alternatively, are there simpler methods to achieve this task?

Answer №1

Imagine you are given the following array:

var collection = [ { "term":"apple", "group": "1"}, { "term":"banana", "group": "1"}, { "term":"orange", "group": "1"}, { "term":"grape", "group": "2"}, { "term":"kiwi", "group": "2"} ]

You can experiment with this function:

function displayTermsByGroups(collection) {
    var currentGroup = 1;
    var result = "";
    collection.forEach(function(item) {
        if(currentGroup < item.group) {
            currentGroup = parseInt(item.group);
            result += "<br>";
        }
        result += item.term + " ";
    })
    return result;
}

This function will generate the following output:

"apple banana orange <br> grape kiwi "

Feel free to customize it according to your requirements.

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

Converting HTML to PDF: Transform your web content into

I have a couple of tasks that need to be completed: Firstly, I need to create a functionality where clicking a button will convert an HTML5 page into a .PDF file. Secondly, I am looking to generate another page with a table (Grid) containing data. The gr ...

What steps are involved in developing a content management system similar to WordPress that can be easily set up within an

My apologies for any language barriers. I am interested in learning how to develop a content management system (CMS) similar to WordPress, which users can install on their own hosting. Basically, I want to create a user-friendly CMS that can be distribut ...

Having trouble submitting the form in ExpressJS - error encountered

Currently, I am in the process of learning ExpressJS and I have encountered an issue while trying to implement the login functionality. Whenever I attempt to submit the form using the POST method, I receive the following error message: "Cannot POST /login" ...

Determining the live total number of Protovis Sparkbar instances

I am currently working on a project where I need to show the ratings and corresponding dates (in string format) from a JSON file in tipsy tooltips. The data consists of a list of dates and ratings. For example: var data = [{"dates":["2010-07-01","2010-07 ...

Exploring the features of NodeJS, diving into the world of mapping,

Currently, I am working in a Node.js environment and dealing with an array of IDs. My goal is to filter these IDs based on the response of another API call. Essentially, I need to check if each ID meets certain criteria specified by this external API. Whi ...

How can the application configuration be sent from MVC to Angular 2?

Looking to upgrade from RC4 => Angular 2.1.0 let element = this.elementRef.nativeElement; let myattr = element.getAttribute("applicationConfig"); Encountering the error: Error: Call to Node module failed with issue: TypeError: native.getAttribute i ...

Analyzing HTML code can disrupt elements related to JavaScript, even though the scripts themselves are

I've developed a script that transforms the Arabic numerals in the body's innerHTML (like 123) into Arabic-Indic numerals (١٢٣), while leaving numbers in tag attributes unchanged and excluding certain tags like script and style. The parser is ...

Optimizing the management of optional post fields in an Express.js application

When creating an endpoint with Express that includes both mandatory and non-mandatory fields in the post request, what is the optimal strategy for handling this? Would it be best to use something like if (field exists in req.body) { set variable } else { ...

Adding an Additional Field to a Mongoose Object

I need to include a new attribute in my object. var _u = await User.findOne({_id},{_id:0, name:1, username:1, group:1}).populate({ path: 'group', select: '-_id title' }) _u.type = 'user' console.log(_u) However, the type ...

Problems arise when using AngularJS' .run function after navigating to a different page

I have encountered an issue with ngRoute while navigating between pages in my web application. The main login page is called index.html, and the routing is controlled by the main js file. However, I face a problem when trying to use a .run block on a speci ...

When clearInterval is used to stop a setInterval, it will not automatically restart if reset with setInterval

I am facing an issue with a countdown timer that I have created using setInterval in JavaScript. The timer is supposed to countdown from one minute at one second intervals. However, when I click the "start" button, it starts the countdown but if I click an ...

What is the best way to utilize jQuery to prevent users under the age of 18 from accessing certain

In my form, I have an input field with a datepicker that displays dates in the format 07/03/2019. After calculating the age based on the selected date, it correctly determines the user's age. However, there is a problem - when the user's age is b ...

The initial item in a pagination/list is double-parsed on an AJAX website using Selenium 3.0.2, Firefox webdriver, and BeautifulSoup 4.5.1

For the past three days, I've been facing a frustrating issue with both Selenium and Bs4. While I suspect Selenium (or my code) to be the culprit. Like many others before me, I'm attempting to scrape data from this website: I'm moving from ...

Attempting to invoke a function containing a promise in Javascript

Calling the function numberOfRedeems(dealId) from another function named setUpData raises an issue where the numberOfRedeems() function, which includes a promise and returns "counter", always returns as undefined when executed within the setUpData function ...

`How can I stop typescript from converting dynamic imports to require()?`

Currently, I am in the process of creating a Discord bot using discord.js. Interestingly, discord.js does not seem to be compatible with ESM modules, which has been causing some complications in my project. As a result, I have resorted to utilizing CommonJ ...

"Encountering issues when trying to retrieve a global variable in TypeScript

Currently facing an issue with my code. I declared the markers variable inside a class to make it global and accessible throughout the class. However, I am able to access markers inside initMap but encountering difficulties accessing it within the function ...

Identifying iOS 5 or above using JavaScript

I've been experimenting with this code snippet to check if the browser is iOS 5 or newer (found on this Stack Overflow thread Detect iOS version less than 5 with JavaScript). function iOSversion() { if (/iP(hone|od|ad)/.test(navigator.platform)) ...

Attempting to create a login and registration form

Hello, I am attempting to create a form that can generate new user accounts and passwords. These values should be stored from the input tag when the user clicks on the register button. Unfortunately, I am encountering an issue where clicking the register ...

Using jquery to toggle active nav links in Bootstrap

I'm currently working on integrating a jQuery function to automatically update the active status of the navigation links in my Bootstrap Navbar. The structure involves a base HTML file that extends into an app-specific base file, which is further exte ...

Why does jwplayer function properly on desktops but not consistently on all mobile devices?

Here is how I set it up: autostart:true file:"//strlb.nava.hu/lbs/navahus/_definst_/amlst:2334206?type=m3u&sessid=U2FsdGVkX1%2BT8isbmDU7Vz56rK8KVCo2xKgOLwwR5JUSq5m5GfKrL4HM%2FrbhwdyJJ0gyyK0X6%2FrAbTjfnsBAqg%3D%3D_2" height:360 id:"videoPlayer" preloa ...