Klatch Baldar
Klatch Baldar

Reputation: 59

Underscore/Lo-Dash _.each not returning array

I was initially trying to do this:

var array = ['A','B','C'];
array = _.each(array, function(item) { return item + '+' });

to get this:

['A+','B+','C+'];

but _.each does not seem to return a function.

I eventually settled on this:

var array = ['A','B','C'];
newArray = [];
_.each(array, function(item) {
  newArray.push(item + '+');
});

but it seems pretty clunky by comparison.

Am I using _.each incorrectly, or is there another function I should be using?

Upvotes: 1

Views: 2397

Answers (3)

Code Whisperer
Code Whisperer

Reputation: 23652

var newArray = _.map(array, function(item) {
  return item + '+';
});

Upvotes: 0

Bergi
Bergi

Reputation: 664484

is there another function I should be using?

Yes. each never returns an array, it just iterates. Use map to produce an array of callback results.

var array = _.map(['A','B','C'], function(item) { return item + '+' });

Upvotes: 6

kinakuta
kinakuta

Reputation: 9037

Making my comment an answer instead - use _.map to return an array. The _.each method will simply iterate through your collection.

Upvotes: 3

Related Questions