How to travel with foreach backwards forward

1

I am doing a blog and I would like the blog entries to be shown from the newest to the oldest, I was wondering if there is any way to go back and forth with a foreach.

The code I have now is this:

<% blogs.forEach(function(blog){ %>
<img src="<%= blog.image %>" style="height: 200px">
<p><h4><%= blog.title %></h4><span><%= blog.category %></span></p>
<p><%= blog.content %></p>

<p><%= moment(blog.createdAt).fromNow() %></p>
    
asked by Varox 16.04.2018 в 14:29
source

3 answers

1

This option is slow but you have to mention it.

Your code would work perfect only if you have to reverse order your arrangement with the < strong> reverse

    <% blogs.reverse() %>
    <% blogs.forEach(function(blog){ %>
    <img src="<%= blog.image %>" style="height: 200px">
    <p><h4><%= blog.title %></h4><span><%= blog.category %></span></p>
    <p><%= blog.content %></p>

    <p><%= moment(blog.createdAt).fromNow() %></p>
    
answered by 16.04.2018 / 15:54
source
2

Instead of using forEach , use% normal% co_ iterating from array size to 0.

<% for(i = blogs.length; i > 0; i--){ %>
<img src="<%= blogs[i].image %>" style="height: 200px">
<p><h4><%= blogs[i].title %></h4><span><%= blogs[i].category %></span></p>
<p><%= blogs[i].content %></p>

<p><%= moment(blogs[i].createdAt).fromNow() %></p>
    
answered by 16.04.2018 в 14:35
0

Try turning over the array you pass in case it is an array maybe this will help you link

    
answered by 16.04.2018 в 14:34