28

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

dylanized
  • 3,765
  • 6
  • 32
  • 44

2 Answers2

71

You can use forEach method

myArray.forEach(function(el, index) {
    // el - current element, i - index
});
wachme
  • 2,327
  • 20
  • 18
  • but when I delete one element in my array, the index won't adapt. What would be the solution for this? – Emanuela Colta Aug 28 '17 at 11:03
  • @Emanuelacolta you can't be deleting your items within the forEach. You should save the index of the elements to delete in separate array and delete them after you finished forEach. (And you need to delete them in reverse order, so that indices of the array do not shift as you delete) – Dimitry K Oct 05 '17 at 17:58
0

@wachme's answer is correct, but to stick with the original question, here is the version using Underscore's _.each (and integrated in template syntax):

<% _.each(myArray, function(el, index) { %>
    Value is <%= el %>, index is <%= index %>.
<% }) %>

The advantage of Array.prototype.forEach is that you don't need to depend on Underscore in your templates. The advantage of _.each is that it has some additional tricks up its sleeves (for example, it also works on objects) and that it works in older JS environments without any need for polyfills.

As an aside, Underscore's _.template can be used instead of EJS, although it has fewer features. Also, the meaning of <%= and <%− is swapped between the two libraries. Naturally, you can always use _.each in Underscore templates.

Julian
  • 4,176
  • 19
  • 40