How To Compare Specific Items In Array Inside Of Basic Lodash Loop
This is the basic JavaScript for loop I'm trying to replace: for (var i=0; i
Solution 1:
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 foundif (ticker) {
// If element found in the array call the function
selectTicker('portfolio', ticker);
// return; // To return from the function
}
Solution 2:
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);
}
Solution 3:
You have to add an argument to the function:
_.times((tickers.length), function( i ) {
if (tickers[i].ticker === selectedTicker) {
selectTicker('portfolio', tickers[i]);
return;
}
});
Post a Comment for "How To Compare Specific Items In Array Inside Of Basic Lodash Loop"