Arrange the array to show 8 elements, ensuring to first review the likes object within the array

I am currently iterating through an array of objects in the following manner:

<% for(post of posts) { %> 
           
            <% if(post.likes > 5){ %> 
            <div class="col">
                <div class="card d-flex flex-column text-white mb-2" style="width: 18rem;">
                    <img src="<%=post.image%>" class="card-img" style="height: 300px;width: auto;" alt="...">
                    <div class="card-img-overlay align-self-end">
                        <h5  style="background-color: white;color: black;border-radius: 10px; text-align: center;" class="card-title"><%=post.title%> </h5>
                        <p style="text-shadow: 0.5px 0.5px 0.5px #00000050;" class="card-text"><%=post.content.slice(0,105)%>...</p>
                        <a href="/home/<%=post._id%>" class="btn btn-primary shadow">Continue Reading</a>
                        
                    </div>
                    <div class="d-flex justify-content-between">
                    <div style="color: black;" class="card-footer bg-transparent"><%=post.likes%> <span> </span> <i style="color: red;" class="fas fa-heart d-inline"></i></div>
                    <% if(!post.date){ %> 
                        <div style="color: black;" class="card-footer bg-transparent">Test Mode <span> </span> <i class="fas fa-calendar-alt"></i></div>
                        <% }else{ %> 
                    <div style="color: black;" class="card-footer bg-transparent"><%=post.date%> <span> </span> <i class="fas fa-calendar-alt"></i></div>
                    <% } %> 
                    </div>
                </div>
            </div>
            
            <% } %> 
            
        <% } %>   

My current code displays all items with likes greater than 5, however, I am aiming to display only 8 items with likes greater than 5. I have spent a considerable amount of time attempting to achieve this without success. Any assistance would be greatly appreciated as I am a beginner in this field!!

Answer №1

Give this code a shot

<% let postCount = 0; %>
<% for(item of items) { %> 
           
            <% if(item.likes > 5 && postCount < 8){ %> 
            <% postCount++ %>
            <div class="col">
                <div class="card d-flex flex-column text-white mb-2" style="width: 18rem;">
                    <img src="<%=item.image%>" class="card-img" style="height: 300px;width: auto;" alt="...">
                    <div class="card-img-overlay align-self-end">
                        <h5  style="background-color: white;color: black;border-radius: 10px; text-align: center;" class="card-title"><%=item.title%> </h5>
                        <p style="text-shadow: 0.5px 0.5px 0.5px #00000050;" class="card-text"><%=item.content.slice(0,105)%>...</p>
                        <a href="/home/<%=item._id%gt;" class="btn btn-primary shadow">Read More</a>
                        
                    </div>
                    <div class="d-flex justify-content-between">
                    <div style="color: black;" class="card-footer bg-transparent"><%=item.likes%> <span> </span> <i style="color: red;" class="fas fa-heart d-inline"></i></div>
                    <% if(!item.date){ %> 
                        <div style="color: black;" class="card-footer bg-transparent">Test Mode <span> </span> <i class="fas fa-calendar-alt"></i></div>
                        <% }else{ %> 
                    <div style="color: black;" class="card-footer bg-transparent"><%=item.date%> <span> </span> <i class="fas fa-calendar-alt"></i></div>
                    <% } %> 
                    </div>
                </div>
            </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

Leveraging jQuery within a method defined in an object using MyObject.prototype.method and the 'this' keyword

Recently, I've started exploring Object-oriented programming in JavaScript and have encountered a challenge. I'm trying to define an object like the example below, where I am using jQuery inside one of the methods. I'm curious about the best ...

Adjusting the header background color and inserting a logo once a specific threshold is reached

Currently, I am designing a website where I need the background color to transition from transparent to black and display a logo once the user scrolls down to a certain point. I am a beginner in javascript and I am facing some difficulties with this task. ...

How can you establish an environmental variable in node.js and subsequently utilize it in the terminal?

Is there a way to dynamically set an environmental variable within a Node.js file execution? I am looking for something like this: process.env['VARIABLE'] = 'value'; Currently, I am running the JS file in terminal using a module whe ...

Navigating fluently in React Native applications

Struggling to grasp the proper implementation of navigation in RN? The provided code snippet should shed light on the current scenario. HeaderConnected is equipped with a menu button component that utilizes a custom navigate prop for opening the Drawer me ...

Create a single line of content for a carousel display

Seeking a solution where I can have a container that slides sideways without stacking in rows, I have exhaustively searched for answers using different keywords like single row, inline, flexbox, and grid but to no avail. Any assistance will be highly appre ...

outputting a specific element in an array using its key

Here is my PHP code snippet: $special_term_id = 55; $special_term_name = $form['shs_term_node_tid_depth']['#options']["'" .$special_term_id. "'"]; echo $special_term_name; When I use the above code, it doesn't work. Ho ...

Error: The validation of a JSON request failed as schema.validate is not a recognized function

As a beginner, I am currently immersed in a node.js API authentication tutorial. Everything was going smoothly until I had to refactor my code into separate files. Now, every time I send a JSON request via Postman, I keep encountering the error message "Ty ...

Transforming an Image URL into base64 format using Angular

I'm currently facing difficulty when attempting to convert a specified image URL into base64. In my scenario, I have a string that represents the image's path. var imgUrl = `./assets/logoEmpresas/${empresa.logoUrl}` Is there a way to directly co ...

While creating a React app, Docker becomes stuck due to a hangup when checking the core-js dependency

I've hit a roadblock in the build process. I'm working on an M1 Mac Mini and have attempted to build in both arm64 and x86_64 terminals, but the outcome is consistently the same. npm info lifecycle @babel/<a href="/cdn-cgi/l/email-protection" ...

"Implement a feature to recognize and handle various file extensions within an npm

I need help with my npm script where I am trying to include both ts and tsx file extensions. My current code snippet is as follows: "test": "mocha ..... app/test/**/*.spec.{ts,tsx}" Unfortunately, the above syntax is not working correctly. Can someone pl ...

What is the best way to simulate a library in jest?

Currently, I am attempting to simulate the file-type library within a jest test scenario. Within my javascript document, this particular library is utilized in the subsequent manner: import * as fileType from 'file-type'; .... const uploadedFil ...

An issue in D3.js where the chart bars are not properly synced with the x-axis labels

Currently delving into the world of d3.js for the first time. In our project, we needed to adjust the width of each bar from .attr('width', xScale.rangeBand()) line 46 to .attr('width', '10') line 50 After making this cha ...

Problem with deploying a Nextjs project on cPanel

I've been struggling to deploy a nextjs project on cPanel. The project consists of only one SSG page. I set the basePath in next.config.js to deploy the project, but I keep getting a 404 page not found error and the page keeps getting called in the ne ...

What is the best way to use JavaScript to conceal all div elements?

Can someone please provide a JavaScript solution to hide all divs on a web page without using jQuery? I am looking for a method that does not involve using the arrays that are associated with document.getElementByTag. If this is not possible, could you p ...

Why is it impossible for me to show the title "individual name:"?

<p id="display1"></p> <p id="display2"></p> var player1= { alias: 'Max Power', skills: ['shooting', 'running'] }; $("#display1").append( "<br/>" + "player alias :" + player1.alia ...

Having trouble with creating SQLite tables using JavaScript within a for loop

I have developed a multi-platform app using AngularJS, JavaScript, Phonegap/Cordova, Monaca, and Onsen UI. In order to enable offline usage of the app, I have integrated an SQLite Database to store various data. After conducting some basic tests, I confir ...

Create an HTML and CSS code that allows you to split paragraph text into columns within a

I am seeking a way to create dynamic paragraph column text using only the https://i.sstatic.net/ZX1AN.png Here is an example of how it could be displayed in HTML: <div> <p> Sed ut perspiciatis, unde omnis iste natus error sit voluptatem ...

Performing numerous asynchronous MongoDB queries in Node.js

Is there a better way to write multiple queries in succession? For example: Space.findOne({ _id: id }, function(err, space) { User.findOne({ user_id: userid }, function(err, user) { res.json({ space: space, user: user}); }); }); It can g ...

Tips for showing ng-repeat items solely when filters are applied by the user

Is there a way to only display elements when a user uses a filter? For instance: $scope.elements = [{name : 'Pablo', age : 23}, {name : 'Franco', age : 98}]; <input type="text" ng-model="searchText" /> <div ng-repeat="elemen ...

What is the best way to notify the JSON code below using jQuery?

I have received a JSON response after using the Reverse Geocoding API from Google. The response includes various address components such as route, sublocality, locality, and political information. { "results": [ { "address_components": [ ...