-1

Below is my ejs code, pulling from my database, how would I go about getting my array to display my array of images and names in reversed order ?

<% posts.forEach(function(post){ %>
            <div class="col-md-3 col-sm-6">
                <div class="thumbnail">
                   <img src="<%= post.image %>">
                   <div class="caption">
                       <h4><%= post.name %></h4>
                   </div>
                   <p>
                       <a href="/posts/<%= post._id %>" class="btn btn-primary">More Info</a>
                   </p>
                </div>
            </div>
        <% }); %>
416seller
  • 1
  • 3

2 Answers2

4

You could do posts.reverse().forEach(... to archieve that.

Wayrex
  • 2,027
  • 1
  • 14
  • 25
  • 2
    It may be worthwhile to [copy the array first](https://stackoverflow.com/questions/7486085/copying-array-by-value-in-javascript), since `.reverse()` will modify `posts` directly before returning it. Otherwise, might be surprised later if `posts` is iterated over again. – Jonathan Lonowski May 28 '18 at 16:22
-1

If Some beginner like me is looking at this question in 2021 or later. You can use the for loop to show the posts array in reverse order. In this case, the above code can be modified in the following way to show it in reverse.

<% for(var i= (posts.length-1); i>=0; i--){ %>
<div class="col-md-3 col-sm-6">
  <div class="thumbnail">
    <img src="<%= posts[i].image %>">
    <div class="caption">
      <h4><%= posts[i].name %></h4>
    </div>
    <p>
      <a href="/posts/<%= posts[i]._id %>" class="btn btn-primary">More Info</a>
    </p>
  </div>
</div>
<% } %>
Joy Karmoker
  • 139
  • 13