Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Looping through Array - Print only once?

Tags:

arrays

loops

ejs

Working on looping through a set of data and adding the names of foods to one array. Current set up below:

Note: The allDBfoods is a collection of food data seeded in the database.

<% var breakfastFoods = []  %>
<% for (var food of allDBFoods) { %>
    <% if (food.breakfast == true ){ %>

        <% breakfastFoods.push(food.name) %>
        <% console.log(breakfastFoods)%>
    <% } %>
<% } %>

This works but returns

[ 'Eggs' ]
[ 'Eggs', 'Bacon' ]
[ 'Eggs', 'Bacon', 'poptarts' ]

I only want it to make one array. Any advice?

like image 807
AndrewLeonardi Avatar asked Jan 20 '26 13:01

AndrewLeonardi


1 Answers

Try to use log outside of for loop:

<% var breakfastFoods = []  %>
<% for (var food of allDBFoods) { %>
    <% if (food.breakfast == true ){ %>    
        <% breakfastFoods.push(food.name) %>
    <% } %>
<% } %>
<% console.log(breakfastFoods)%>
like image 86
Stanislovas Kalašnikovas Avatar answered Jan 23 '26 03:01

Stanislovas Kalašnikovas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!