Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fuse.js search in array of strings

I was trying to implement fuse.js to my app where I have array of strings without any key.

['Kelly', 'Creed', 'Stanley', 'Oscar', 'Michael', 'Jim', 'Darryl', 'Phyllis', 'Pam', 'Dwight', 'Angela', 'Andy', 'William', 'Ryan', 'Toby', 'Bob']

When I try to configure the fuse.js I'm getting no results, because of unspecified key.

var options = {
  shouldSort: true,
  threshold: 0.6,
  location: 0,
  distance: 100,
  maxPatternLength: 32,
  minMatchCharLength: 1,
  keys: [
    "title",
    "author.firstName"
  ]
};
var fuse = new Fuse(list, options); // "list" is the item array
var result = fuse.search("");

is it possible to perform fuzzy search on plain array, or do I need to convert everything to be an object?

like image 611
Lukáš Václavek Avatar asked Dec 04 '19 14:12

Lukáš Václavek


1 Answers

It's possible to do a search on an array of strings. You need to not specify a keys property in the options object.

Here's an example:

const list = ['Kelly', 'Creed', 'Stanley'];

// your options can be anything you want, but don't include
// the keys property
let options = {
  shouldSort: true,
  threshold: 0.6,
  location: 0,
  distance: 100,
  maxPatternLength: 32,
  minMatchCharLength: 1,
  // don't include the keys property
};

const fuse = new Fuse(list, options);

let result = fuse.search('Kelly');
// result will be:
// {"item":"Kelly","refIndex":0}
// here, refIndex is the index of the element in list
like image 138
Eric Wiener Avatar answered Oct 20 '22 23:10

Eric Wiener