Andrés Orozco
Andrés Orozco

Reputation: 2661

How to loop over and array with underscore

I'm trying to loop over an Array using Underscore, I have this:

var friends = [
  {
    name: 'Jimmy',
    age: 21
  },
  {
    name: 'Anna',
    age: 19
  },
  {
    name: 'Alina',
    age: '22'
  },
  {
    name: 'Carl',
    age: '22'
  }
];

var names = _(friends).pluck('name');

for(i = 0; i < friends.length; i++){
  $('ul').append('<li>' + names[i] + '</li>');
}
<script src="http://underscorejs.org/underscore-min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<ul></ul>

I'm trying to do the same using underscore's each method, but I can't achieve it, I'm trying doing something like this:

_(friends).each(function(namessss, i){
  $('ul').append('<li>' + names[i] + '</li>');
});

This actually works, but what I don't understand is why?! What's the first parameter for, it doesn't matter what I write there, it works and I wonder how to do this, and why this way works, thanks.

Upvotes: 2

Views: 8871

Answers (3)

Bobby Orndorff
Bobby Orndorff

Reputation: 3335

The each method has the syntax...

_.each(list, callbackFunc);

where callbackFunc has the syntax...

function callbackFunc(element, index, list) {}

Your code just happens to work because you stored the name values in the names array which you are then accessing using the index passed to your callback function. A better way to write the code would be...

_(friends).each(function(friend){
  $('ul').append('<li>' + friend.name + '</li>');
});

Upvotes: 0

Keith Nicholas
Keith Nicholas

Reputation: 44288

this would be a reasonably typical way :-

var friends = [
  {
    name: 'Jimmy',
    age: 21
  },
  {
    name: 'Anna',
    age: 19
  },
  {
    name: 'Alina',
    age: '22'
  },
  {
    name: 'Carl',
    age: '22'
  }
];

var names = _(friends).pluck('name');

_.each(names, function(name){
  $('ul').append('<li>' + name + '</li>');
});
<script src="http://underscorejs.org/underscore-min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<ul></ul>

Upvotes: 1

Andy Noelker
Andy Noelker

Reputation: 11269

According to the documentation:

Each invocation of iteratee is called with three arguments: (element, index, list). If list is a JavaScript object, iteratee's arguments will be (value, key, list)

Your code works no matter what you write for that first argument, because you never actually use that argument (the value itself). Instead you just reference an index on the names array which you have defined outside of this loop.

If you'd like to actually use the value in the each loop, you can use something like this:

_(friends).each(function(friend, i){
  $('ul').append('<li>' + friend.name + '</li>');
});

Upvotes: 2

Related Questions