Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

262
Views
¿La mejor manera de verificar la mejor coincidencia contiene String?

Tengo una cadena y quiero determinar si la mejor cadena está contenida en otra cadena.

Trataré de explicar por código JS como este:

 function A(){ var str = "The best way to check the best match contains String?"; if(str.includes("The")){ //<== This is not the best match, but currently return this return "1"; } if(str.includes("The best")){ return "2"; } if(str.includes("The best way1")){ return "3"; } if(str.includes("The best way")){ //<=== Should to return this return "4"; } }

No quiero cambiar las condiciones si a mano. Porque tal vez la verificación de la lista y los resultados que desea devolver son dinámicos o se cargan desde algún lugar como:

 const objCheck = { "The": "1", "The best": "2", "The best way1": "3", "The best way": "4" }

¿Alguna idea para esto?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Puede usar Object.entries() en su objeto para obtener una matriz de pares clave-valor de la forma:

 [["The", "1"], ["The best": "2"], ...]

Arriba, una matriz interna representa una entrada (es decir, una clave, un par de valores de su objeto). Una vez que tenga esta matriz, puede .sort() en función de la longitud, de modo que las entradas con la clave más larga aparezcan primero en su matriz. Una vez ordenada, puede usar .find() para encontrar la primera entrada que tiene una clave incluida en su str de búsqueda. Por último, puede usar ?.pop() para tomar el valor numérico asociado con la clave que se encuentra. El ?. aquí está el operador de encadenamiento opcional que se utiliza para garantizar que no intentemos llamar a .pop() si .find() no puede encontrar ninguna entrada:

 const objCheck = { "The": "1", "The best": "2", "The best way1": "3", "The best way": "4" }; function findBestMatch(str, obj){ return Object.entries(obj) .sort(([a], [b]) => b.length - a.length) .find(([substr]) => str.includes(substr)) ?.pop(); } var str = "The best way to check the best match"; console.log(findBestMatch(str, objCheck));

Si necesita algo un poco más eficiente, puede evitar la clasificación manteniendo el valor máximo visto hasta ahora mientras recorre su matriz:

 const objCheck = { "The": "1", "The best": "2", "The best way1": "3", "The best way": "4" }; function findBestMatch(str, obj){ let res, best = -Infinity, entries = Object.entries(obj); for(const [substr, num] of entries) { if(substr.length > best && str.includes(substr)) { best = substr.length; res = num; } } return res; } var str = "The best way to check the best match"; console.log(findBestMatch(str, objCheck));

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!