Home > OS >  loop trough two arrays of objects with include() and return nearest/exact match
loop trough two arrays of objects with include() and return nearest/exact match

Time:06-25

I know, that there are many similar questions like this, but I cannot find an answer to my case.

So I am struggling with the following:

I have two array of objects which I am looping trough each other and am trying to fish out a street name. The catch is, to get only the name, which is nearest. I'll explain it below:

const obj1 = [
{ name: "I am the one and only", address: "street name 123, 456" },
{ name: "I am here only to fill up the place", address: "to not be a 1 element long array of objects"}
]

const obj2 = [
{ name: "testA", street: "street name 123" },
{ name: "testB", street: "street name 1" },
{ name: "testC", street: "street name" }
]

for ( let i of obj1 ) {
  for ( let j of obj2 ) {
    if(i.address.includes(j.street)) {
      console.log(i, j)
    }
  }
}

expected output:

{
  address: "street name 123, 456",
  name: "I am the one and only"
}, {
  name: "testA",
  street: "street name 123"
}

what I got:

{
  address: "street name 123, 456",
  name: "I am the one and only"
}, {
  name: "testA",
  street: "street name 123"
}
{
  address: "street name 123, 456",
  name: "I am the one and only"
}, {
  name: "testB",
  street: "street name 1"
}
{
  address: "street name 123, 456",
  name: "I am the one and only"
}, {
  name: "testC",
  street: "street name"
}

Link to my playground: CodeSandboxLink

My question is, how to achieve my expected result? Tried it with regex, but it cannot find any formula, that could help in my case.

CodePudding user response:

An approach.

You could build a score list and choose the one with the largest score.

The score is made of matching strings and their length.

const
    data1 = [{ name: "I am the one and only", address: "street name 123, 456" }, { name: "I am here only to fill up the place", address: "to not be a 1 element long array of objects"}],
    data2 = [{ name: "testA", street: "street name 123" }, { name: "testB", street: "street name 1" }, { name: "testC", street: "street name" }],
    scores = {};

data1.forEach(({ address }, i) => {
    data2.forEach(({ street }, j) => {
        if (address.includes(street)) scores[[i, j].join('|')] = street.length / address.length;
    });
});

console.log(scores);

  • Related