Reputation: 59
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
Reputation: 23652
var newArray = _.map(array, function(item) {
return item + '+';
});
Upvotes: 0
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
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