简体   繁体   中英

Fast way to search an array of objects for a matching key/value pair

I have an array of about 950 objects, each containing basic information about soccer players for me to list on the page. I'm adding search functionality to this wherein I check the "name" key in each object and return similar results. This code snippet assumes I have an empty array for the results (results = []), and obvs I'm looping using underscore (see: lodash):

_.each(players, function(player, i){

  if(player.name.search(searchString) !== -1){
    results.push(item);
  }

})

This works well, but takes FOREVER. Okay it actually takes about 1 second but it more or less destroys the browser and eats memory like chocolate cake while it's running and is a very sluggish UX.

The ask: Is there a better way to do this (better == quicker)?

I can put my actual data in a jsfiddle/jsbin/jswhatever if that helps.

Really not sure about performance, but I would imagine that _.filter would better suited for your issue.

var results = _.filter(players, function(player){
  return player.name.toLowerCase().indexOf(searchString.toLowerCase()) !== -1;
});
  • You can find out whether the search -function is faster or slower than other 'checks' like indexOf or whatever.

  • What you can do is to have the players array sorted by the name-property already. Then you can go through the array alphabetically and skip the ranges of letters that do not match the first letter of your search term. That way you have some sort of indexing.

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