简体   繁体   中英

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<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

在此处输入图片说明

在此处输入图片说明

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
}

You have to add an argument to the function:

_.times((tickers.length), function( i ) {
    if (tickers[i].ticker === selectedTicker) {
        selectTicker('portfolio', tickers[i]);
        return;
    }
});

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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM