krisk / Fuse

Lightweight fuzzy-search, in JavaScript
https://fusejs.io/
Apache License 2.0
17.77k stars 754 forks source link

How I can search in the nested array of strings? #630

Closed vedmant closed 2 years ago

vedmant commented 2 years ago

Here is my data:

[
  [
    'test1',
    'test2',
    'test3-match',
  ],
  [
    'test11',
    'test12-match',
    'test13',
  ],
  [
    'test21',
    'test22',
    'test23',
  ],
]

How I can search this array? I need to return only subarrays that include any matches.

hrushi2003 commented 2 years ago

function Search(array, searchItem){ for(let i = 0; i < array.length; i++){ for(let j = 0; j < array[i].length; j++){ if(array[i][j] === searchitem){ return array[i];}}} } I think it will help @vedmant

vedmant commented 2 years ago

@hrushi2003 How and where I can use this code?

hrushi2003 commented 2 years ago

i have written the code in javascript and defined the function Search that takes two arguments array and the search item.give the arrray containing sub arrays to the array agument and give search item which you want find in the given array in the searchItem argument. @vedmant

vedmant commented 2 years ago

@hrushi2003 So how to use it with Fuse.js?

github-actions[bot] commented 2 years ago

This issue is stale because it has been open 30 days with no activity. Remove stale label or comment or this will be closed in 5 days

BenJenkinson commented 2 years ago

I don't think fuse.js can understand the structure of your array as it is, but I was able to search it by transforming it first.

For example, given your array of arrays, of type string[][]:

[
  ["test1", "test2", "test3-match"],
  ["test11", "test12-match", "test13"],
  ["test21", "test22", "test23"],
];

You can map them first, to type { foo: string[] }[], e.g.:

[
  { foo: ["test1", "test2", "test3-match"] },
  { foo: ["test11", "test12-match", "test13"] },
  { foo: ["test21", "test22", "test23"] }
]

... and then feed that to fuse.js, like so:

// Your original list.
const list = [
  ["test1", "test2", "test3-match"],
  ["test11", "test12-match", "test13"],
  ["test21", "test22", "test23"],
];

// Map the list to a structure that `Fuse.js` can understand.
const mapped = list.map((x) => {
  return {
    foo: x,
  };
});

// Specify the `key` option, with the placeholder property name we want to search.
const options = {
  keys: ["foo"],
};

const fuse = new Fuse(mapped, options);

// Do the search..
return fuse.search("match");

The results would look like this:

[
  {
    "item": {
      "foo": ["test1", "test2", "test3-match"]
    },
    "refIndex": 0
  },
  {
    "item": {
      "foo": ["test11", "test12-match", "test13"]
    },
    "refIndex": 1
  }
]