7

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?

Lukáš Václavek
  • 442
  • 1
  • 6
  • 12

1 Answers1

4

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
Eric Wiener
  • 4,929
  • 4
  • 31
  • 40
  • If you have .js file, you can also use let colordatavalues = Object.values(list); const fuse = new Fuse(colordatavalues, options); – Bitfinicon Feb 18 '22 at 12:43