Why is the array not pushing correctly into r during the loop?
If I change
if((pivot + originArr[c]) <= 5)
to if((pivot + originArr[c]) <= 3)
My result is incorrect:
[ [ 0, 1, 2, 3, 4 ],
[ 0, 1, 2, 3, 4 ],
[ 0, 1, 2, 3, 4 ],
[ 0, 2, 3 ],
[ 1, 2, 3 ] ]
The expected result should be[ [ 0, 1, 2], [ 0, 1, 3], [ 0, 1, 4], [ 0, 2, 3 ] ]
If r is not empty, it will recursively send the first iteration result back to the function for computation until "r" is empty. Instead of pushing individual arrays to "r" for every c loop.
var data = [0, 1, 2, 3, 4, 5];
function compute(originArr, filterArr) {
var r = [];
var arr;
let firstLoop = false;
if (filterArr.length == 0) {
firstLoop = true;
arr = originArr;
} else {
arr = filterArr;
}
arr.forEach(function(i, index) {
var pivot;
if (firstLoop) {
pivot = index;
} else {
pivot = parseInt(i.slice(-1));
}
var nextIndex = pivot + 1;
console.log(pivot, nextIndex);
for (var c = nextIndex; c < originArr.length; c++) {
let tempResult = [];
console.log(c);
if (pivot + originArr[c] <= 3) {
if (firstLoop) {
tempResult.push(index);
} else {
tempResult = i;
}
tempResult.push(c);
console.log(tempResult);
r.push(tempResult); // suppose to push [0,1], [0,2], [0,3], [1,2] for the first iteration
}
}
});
if (r.length > 0) {
return compute(originArr, r);
} else {
return arr;
}
}
console.log(compute(data, []));
//Final result should be [[0,1,2]]