node.jsexpressunderscore.jsejspartials

Inside Express/EJS templates, what is cleanest way to loop through an array?


I have an Express.js app set up using EJS templates. I successfully looped through an array with classic JS syntax:

<% for (var i = 0; i < myArray.length; i++) { 
    this = myArray[i];
    // display properties of this
} %>

But I'm wondering, is there a cleaner way to do this?

Specifically, can I use Underscore or Lodash to loop through with .each ? thank you


Solution

  • You can use forEach method

    myArray.forEach(function(el, index) {
        // el - current element, i - index
    });