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

165
Views
Ir al elemento siguiente o anterior si no existe una clave en una matriz

Lo que estoy tratando de lograr me parece bastante complicado. Quiero pasar de un elemento a otro, lo que puedo lograr fácilmente con este fragmento de código, como se muestra a continuación.

Suponiendo que tengo esta matriz de objetos

 const arr = [ { answered: true, duration: 15 }, { answered: true, duration: 15 }, { duration: 15 }, { answered: true, duration: 15 }, { duration: 15 }, ];

Luego uso este fragmento de código para lograr pasar al siguiente elemento que funciona bien.

 let count = 0; arr[count + 1]; return arr

Sin embargo, lo que estoy tratando de lograr es pasar al siguiente elemento que no tiene una answered: true : valor Lo que significa que si estoy comenzando desde el índice 0, el siguiente botón debería moverse al tercer índice porque no tiene una answered: true

Para mayor claridad, si puedo obtener elementos que no contienen answered filtradas, debo poder hacer un count + 1 que también me puede mover al siguiente índice de matriz en el resultado filtrado.

Suponiendo que el resultado filtrado es

 const filtered = [ { duration: 15 }, { duration: 15 }, ]

Debería poder filtered[count + 1]

Gracias

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

0

Suponiendo que tanto el iterador como la matriz son parte de un estado global, la función click() tiene como objetivo simular un clic de botón que mencionó.

La función recorre la matriz y comienza a buscar el siguiente elemento sin respuesta, comenzando desde el valor de iteración global. La función establece que el iter sea uno después del elemento actual que no se responde, de modo que cuando se vuelve a llamar a la función, comienza a buscar desde el siguiente elemento.

La función reset() simplemente reinicia la búsqueda desde el principio.

 let iter = 0 const arr = [{ answered: true, duration: 15 }, { answered: true, duration: 15 }, { duration: 10 }, { answered: true, duration: 15 }, { answered: true, duration: 15 }, { answered: true, duration: 15 }, { answered: true, duration: 15 }, { duration: 3 }, { duration: 1 }, ]; const findNext = () => { for (let i = iter; i < arr.length; i++) { if (!('answered' in arr[i]) || !arr[i].answered) { document.getElementById("resultIndex").innerHTML = `Result id: ${i}`; document.getElementById("result").innerHTML = `Result body: ${JSON.stringify(arr[i])}`; iter = i + 1 return } } } const reset = () => { iter = 0 document.getElementById("resultIndex").innerHTML = `Result id: none`; document.getElementById("result").innerHTML = `Result body: none`; }
 <div> <button onClick={findNext()}>Next</button> <button onClick={reset()}>Reset</button> </div> <div> <div id='resultIndex'>Result id: none</div> <div id='result'>Result body: none</div> </div>

about 4 years ago · Juan Pablo Isaza Report

0

Puede filtrar la matriz con elementos que no contengan answered y luego repetirlos de la forma habitual.

 var index = 0; const arr = [ { answered: true, duration: 15 }, { answered: true, duration: 15 }, { duration: 15 }, { answered: true, duration: 15 }, { duration: 15 }, { answered: true, duration: 15 }, { answered: true, duration: 15 }, { duration: 15 }, { answered: true, duration: 15 }, { duration: 15 }, ]; function findNext() { for (item in arr) { if (!arr[item].hasOwnProperty('answered')) { document.getElementById("index").setAttribute('value',item); break; } } }
 <button onClick="findNext()">Find next</button> <input type="text" value="" id="index">

about 4 years ago · Juan Pablo Isaza Report

0

Deberías intentar algo como esto:

 const arr = [ { answered: true, duration: 15 }, { duration: 15 }, { answered: true, duration: 15 }, { duration: 15 } ] var i = 0 var missing for (const element of arr) { if (!element.answered) { missing = element break } i++ } console.log(missing) console.log(i)
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!