¿Cuál sería el reemplazo ideal para los bucles for anidados en términos de rendimiento y facilidad de lectura del código, si tengo más de 8 bucles for (además de dos bucles for) donde estoy formando dos listas de matrices que utilizo para concluir con una sola instrucción if ? para producir un resultado.
La base de datos tiene varias filas como:
{ id: 12345 creator: "John" number: 2.5 type: 1 } { id: 45678 creator: "Alex" number: 2.0 type: 2 }
// create array of elements with type:1 chat.find({"type":1}).toArray(function(err, res){ const array1_id = []; const array1_creator = []; const array1_number = []; // form array for each element for(a=0;a<res.length;a++){ array1_id.push(res[a].id); array1_creator.push(res[a].creator); array1_number.push(res[a].number); } // create array of elements with type:2 chat.find({"type":2}).toArray(function(err, res){ const array2_id = []; const array2_creator = []; const array2_number = []; // form array for each element for(b=0;b<res.length;b++){ array2_id.push(res[a].id); array2_creator.push(res[a].creator); array2_number.push(res[a].number); } outerloop: for(c=0;c<array1_id.length;c++){ // id (type: 1 row) var resNum1_id = array1_id[c]; for(c1=0;c1<array1_creator.length;c1++){ // creator (type: 1 row) var resNum1_creator = array1_creator[c1]; for(c2=0;c2<array1_number.length;c2++){ // number (type: 1 row) var resNum1_number = array1_number[c2]; innerloop: for(d=0;d<array2_id.length;d++){ id (type: 2 row) var resNum2_id = array2_id[d]; for(d1=0;d1<array2_creator.length;d1++){ creator (type: 2 row) var resNum2_creator = array2_creator[d1]; for(d2=0;d2<array2_number.length;d2++){ // number (type: 2 row) var resNum2_number = array2_number[d2]; // find rows where condition is true if(resNum1_number>=resNum2_number){ console.log resNum1_id+ resNum1_creator+ resNum1_number+ "\n"+ resNum2_id+ resNum2_creator+ resNum2_number+ ); break outerloop; } } } } } } } }); });
Simplemente use dos bucles para recorrer las dos matrices de resultados, comparando los valores num
de cada uno.
// create array of elements with type:1 chat.find({ "type": 1 }) .toArray(function(err, res1) { // create array of elements with type:2 chat.find({ "type": 2 }) .toArray(function(err, res2) { for (let i = 0; i < res1.length; i++) { for (let j = 0; j < res2.length; j++) { if (res1[i].num >= res2[j].num) { console.log(res1[i].id + res1[i].creator + res1[i].num + "\n" + res2[i].id + res2[i].creator + res2[i].num); return; } } } }); });