Reputation: 39018
This is the basic JavaScript for loop I'm trying to replace:
for (var i=0; i<tickers.length; i++) {
if (tickers[i].ticker === selectedTicker) {
selectTicker('portfolio', tickers[i]);
break;
}
}
Here is the lodash version
_.times((tickers.length), function() {
if (tickers[i].ticker === selectedTicker) {
selectTicker('portfolio', tickers[i]);
return;
}
});
Obviously this errors out currently, because there is no [i]
variable set in the lodash version.
The lodash version is much more readable imho, just do this many times the length of my tickers array.
However I need to compare the ticker of each object to the selectedTicker
.
UPDATE: Adding screenshot and link to prove to some asking that _lodash is faster than native Javascript.
http://jsperf.com/forloop-vs-each-from-lodash
Upvotes: 0
Views: 264
Reputation: 87203
You can use _.find()
var ticker = _.find(tickers, {'ticker': selectedTicker});
// `find()` returns an object if the element is found in array
// it returns `undefined` if not found
if (ticker) {
// If element found in the array call the function
selectTicker('portfolio', ticker);
// return; // To return from the function
}
Upvotes: 2
Reputation: 3358
You need to pass i
into the callback in the lodash function. This should work:
_.times((tickers.length), function(i) {
if (tickers[i].ticker === selectedTicker) {
selectTicker('portfolio', tickers[i]);
return;
}
});
Also, if you're able to use es6 syntax, you can achieve the same result by using filter
var ticker = tickers.filter(t => t.ticker === selectedTicker)[0];
if(ticker){
selectTicker('portfolio', ticker);
}
Upvotes: 1
Reputation: 2709
You have to add an argument to the function:
_.times((tickers.length), function( i ) {
if (tickers[i].ticker === selectedTicker) {
selectTicker('portfolio', tickers[i]);
return;
}
});
Upvotes: 1