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

281
Views
Pregunta de Javascript foreach: cómo seleccionar el elemento numérico para formar una nueva matriz

Tengo algunas tareas que manejar en mi trabajo diario, por lo que necesito hacerlo de forma automática. mi tarea es:

  1. se enviarán algunos mensajes a mi IM, y necesito agregar el primer, segundo y tercer número a cada enlace con un "|".
  2. si solo hay 2 números en la recta numérica, se necesita un 0 en primer lugar.

Por ejemplo, en el ejemplo cleanResult, necesito que se haga así:

 finalResult = ["https://www.example.com/firstlink|500", "https://www.example.com/firstlink|150", "https://www.example.com/firstlink|30", "https://www.exmaple.com/secondlink|600", "https://www.exmaple.com/secondlink|150", "https://www.exmaple.com/secondlink|30", "https://www.example.com/thirdlink|500", "https://www.example.com/thirdlink|150", "https://www.example.com/thirdlink|30", "https://www.example.com/forthlink|600", "https://www.example.com/forthlink|100", "https://www.example.com/forthlink|20", "https://www.example.com/fithlink|0", "https://www.example.com/fithlink|200", "https://www.example.com/fithlink|50" ]

Aquí están los códigos que había hecho hasta ahora:

 const urlRegex = /(https?\:\/\/)?([^\.\s]+)?[^\.\s]+\.[^\s]+/gi; const digitRegex = /^(?=.*\d)[\d ]+$/; cleanResult = ["https://www.example.com/firstlink", "https://www.exmaple.com/secondlink", "https://www.example.com/thirdlink", "500 150 30", "https://www.example.com/forthlink", "600 100 20", "https://www.example.com/fithlink", "200 50" ] cleanResult.forEach((item, index) => { if (item.match(digitRegex)) { //codes I don't know how to do... } })
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

¿Los elementos en cleanResult siempre son una URL o un número? En ese caso, podría verificar el primer carácter de la cadena para ver si es un número (básicamente, una URL que no sea). Si no es una URL, sabemos que son números y podemos hacer algo con la URL, que debería ser el elemento anterior:

 // If it's a URL, we will store it here for future use let currentURL = '' cleanResult.forEach((item, index) => { // Get the first character of this string const first = item[0] if (!Number.isInteger(first)) { // This is NOT a number, so must be a URL, // let's store it in our variable to use in the next loop currentURL = item } else { // This IS a number, which means we need to do a few things: // 1. Split into separate numbers // 2. Create a new URL pattern from each number // 3. Push to finalResult // 1. Split by tab delimiter (?) // splits by tab, and returns an array const numbers = item.split('\t') // 2. Create a new URL pattern from each number numbers.forEach((n) { // This should now give you the URL + | + the number: // ex: https://example.com/firstlink|500 const newURL = currentURL + '|' + n // 3. push to the finalResult array finalResult.push(newURL) }) } })

No lo he probado, pero este es el proceso que generalmente uso: divídalo en tareas más pequeñas y dé un paso a la vez. Tampoco usé expresiones regulares, solo para hacerlo más fácil. Suponemos que recibirá una URL o una lista de números separados por una tabulación. Esto significa que puede permitirse mantenerlo un poco simple.

Estoy seguro de que hay formas mucho más eficientes de hacerlo y en muchas menos líneas, pero si solo estás aprendiendo JS o programando, no hay nada de malo en ser más detallado para que puedas entender los conceptos iniciales.

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!