string-similarity
string-similarity copied to clipboard
Feature suggestion - pass array of objects as targets for findBestMatch function
Use case:
Instead of wanting to compare ["foo","bar","baz"], it can be useful to pass in an array of objects for which you want to compare one property, i.e.
[
{ name: "foo", otherProperty: 23 },
{ name: "bar", otherProperty: 27 },
{ name: "baz", otherProperty: 99 }
]
and instruct the function to compare based on the name property, but return the whole object in the response.
I have already created a PR #124 for this. Just need approval
This use case is too specific and too easily adapted to work with the existing interface of the library. What if I wanted it to return the index instead of the property? Or wanted it to select a key on an object within an object within the root-level list?
To adapt the existing interface to operate on this data, you could wrap it in a function:
function findBestMatchForObject(mainString, targets, key) {
const match = findBestMatch(mainString, targets.map((o) => o[key]));
for (const o of targets) {
if (o[key] === match) {
return o;
}
}
}
If you really can't afford the slight performance loss in creating an extra list and iterating an extra time (which is unlikely, this is JS, and the findBestMatch function does a lot more work than the aforementioned additional work), then I would advise just copying the code or forking the project. It is MIT.