如何避免多个嵌套循环



如果我有超过8个用于循环(除了两个用于循环(,并且我正在形成两个数组列表,我使用这两个列表只得出一个if语句以产生结果,那么在性能和易读代码方面,什么是嵌套的理想替代品。

数据库有多行,如:

{
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;
}

}
}
}
}
} 
}
});
});

只需使用两个循环在两个结果数组上循环,比较每个数组的num值。

// 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;
}
}
}
});
});

最新更新