0

Hi i need to order the data according to the fuzzy matching of 2 variables

Consider i have a string :"pet" and Amount 50

I have an object array as like below:

[{"des":"permanent","amount":100}, {"des":"petrol","amount":1000}]

I need an array as below

[{"des":"petrol","amount":100}, {"des":"permanent","amount":1000}] if suppose petrol is highest matching also its nearer to the value 50.

I used fuzzy npm package as follows:

var options = {
               extract: function(el) { return el.description; }
            };
            var results = fuzzy.filter(description, res, options);

But here i can check for only string, but how can i do also for amount?? Thanks in advance

ggorlen
  • 44,755
  • 7
  • 76
  • 106
Subburaj
  • 5,114
  • 10
  • 44
  • 87

1 Answers1

1

Your specification isn't entirely clear, but it seems like you want sorting (changing the order of elements based on some critieria) rather than filtering (removing elements based on some criteria).

There are two possibilities:

  1. You want to sort by fuzzy score on the des string value, then break ties by the amount proximity.
  2. You want to sort by some aggregate weight between the fuzzy des score and by the amount proximity.

Here's the first option:

const search = {des: "pet", amount: 10};
const data = [
  {des: "pet", amount: 1000},
  {des: "petrol", amount: 38},
  {des: "petrol", amount: -17},
  {des: "pets", amount: 9},
  {des: "pet", amount: 999},
];

data.sort((a, b) => {
  const {score: desA} = fuzzy.match(search.des, a.des);
  const {score: desB} = fuzzy.match(search.des, b.des);
  
  if (desA !== desB) {
    return desB - desA;
  }
  
  return Math.abs(search.amount - a.amount) -
         Math.abs(search.amount - b.amount);
});

console.log(data);
<script src="https://unpkg.com/fuzzy@0.1.3/lib/fuzzy.js"></script>

The second option is more involved, so I'll describe it on a high level. Use fuzzy.match to figure out the score for each des string, figure out how close amount is to the search target, normalize these to the same scale (probably 0 through 1), then weigh the scores by some amount to give a final score. Sort on the final score for each element.

Be careful: fuzzy.match().score returns Infinity for perfect matches, so you might want to convert that to 0 for certain operations.

ggorlen
  • 44,755
  • 7
  • 76
  • 106