JavaScript fuzzy search

前端 未结 7 851
渐次进展
渐次进展 2020-12-24 03:39

I\'m working on this filtering thing where I have about 50-100 list items. And each items have markup like this:

  • 相关标签:
    7条回答
    • 2020-12-24 04:31

      I wasn't satisfied with list.js, so I created my own. This is probably not exactly fuzzy search, but I don't know what to call it. I simply wanted it to match a query without regard to the order of my words in the query.

      Consider the following scenario:

      • a collection of articles in memory exists
      • order of query words appearance doesn't matter (e.g. "hello world" vs "world hello")
      • The code should be easily readable

      Here is an example:

      var articles = [{
        title: '2014 Javascript MVC Frameworks Comparison',
        author: 'Guybrush Treepwood'
      }, {
        title: 'Javascript in the year 2014',
        author: 'Herman Toothrot'
      },
      {
        title: 'Javascript in the year 2013',
        author: 'Rapp Scallion'
      }];
      
      var fuzzy = function(items, key) {
        // Returns a method that you can use to create your own reusable fuzzy search.
      
        return function(query) {
          var words  = query.toLowerCase().split(' ');
      
          return items.filter(function(item) {
            var normalizedTerm = item[key].toLowerCase();
      
            return words.every(function(word) {
              return (normalizedTerm.indexOf(word) > -1);
            });
          });
        };
      };
      
      
      var searchByTitle = fuzzy(articles, 'title');
      
      searchByTitle('javascript 2014') // returns the 1st and 2nd items
      

      Well, I hope this helps someone out there.

      0 讨论(0)
    提交回复
    热议问题