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

185
Views
¿Cómo optimizar el mecanografiado anidado para el bucle de O (n ^ 2) a O (n) o similar?

Tengo dos matrices de objetos, a saber, arr1 y arr2 suponiendo que la longitud de ambos sea igual. Ambos tienen {id: 'some random id', ...} estructura interna. Quiero iterar a través de cada objeto en arr1 y agregar un parámetro checked=false si la id de ese objeto no pertenecía a arr2 de lo contrario, agregue un checked=true .

Aquí está mi código actual:

 for (const i of arr1) { i.checked = false; for (const j of arr2) { if (i.id === j.id) { i.checked = true; } } }

¿Cómo lo optimizo? Se agradece cualquier sugerencia menor que O (n ^ 2).

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

0

Puede crear un conjunto, tienen acceso O (1) haciendo que su ciclo sea O (n)

 const idSet = new Set(arr2.map(i => i.id)) for (const i of arr1) { i.checked = idSet.has(i.id); }
about 4 years ago · Juan Pablo Isaza Report

0

Puede usar Set para preparar ID de la segunda matriz y luego usar Set.prototype.has que tiene la operación O(1).

 const arr1 = [{id: 1}, {id: 2}, {id: 3}, {id: 4}] const arr2 = [{id: 2}, {id: 5}, {id: 4}, {id: 6}] const ids = new Set(arr2.map(({ id }) => id)) for (const item of arr1) { item.checked = ids.has(item.id) } console.log(arr1) /* Result [ { id: 1, checked: false }, { id: 2, checked: true }, { id: 3, checked: false }, { id: 4, checked: true } ] */

Punto de referencia rápido:

 Running "Array check (1000 elements)" suite... Progress: 100% Set.has: 15 671 ops/s, ±0.38% | fastest two loops: 543 ops/s, ±0.48% | slowest, 96.54% slower Finished 2 cases! Fastest: Set.has Slowest: two loops
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!