Sé que hay muchas preguntas similares como esta, pero no puedo encontrar una respuesta a mi caso.
Así que estoy luchando con lo siguiente:
Tengo dos conjuntos de objetos que estoy enlazando entre sí y estoy tratando de encontrar el nombre de una calle. El problema es obtener solo el nombre, cuál es el más cercano. Te lo explico a continuación:
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) } } }Rendimiento esperado:
{ address: "street name 123, 456", name: "I am the one and only" }, { name: "testA", street: "street name 123" }lo que obtuve:
{ 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" }Enlace a mi patio de recreo: CodeSandboxLink
Mi pregunta es, ¿cómo lograr el resultado esperado? Lo probé con expresiones regulares, pero no puede encontrar ninguna fórmula que pueda ayudar en mi caso.
Un acercamiento.
Puede crear una lista de puntajes y elegir el que tenga el puntaje más alto.
La partitura está hecha de cuerdas a juego y su longitud.
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);