I am trying to calculate the cartesian product [all possible 4 number combos given 4 arrays with multiple integers]. I wrote a rather unsophisticated but fairly straightforward nested for loop to initially generate all possible subarrays arrays [135].
here is the code:
const pincArr1 = [1, 2, 4];
const pinacrr2 = [3, 2, 6];
const pincArr3 = [5, 4, 6, 2, 8];
const pincArr4 = [7, 4, 8];
const possiblecombos = (array1, array2, array3, array4) => {
const pinSequence = [];
for (let a = 0; a < array1.length; a++) {
for (let b = 0; b < array2.length; b++) {
for (let c = 0; c < array3.length; c++) {
for (let d = 0; d < array4.length; d++) {
pinSequence.push([
array1[a].concat(array2[b]).concat(array3[c]).concat(array4[d]),
]);
}
}
}
}
return pinSequence;
};
console.log(possiblecombos([pincArr1, pinacrr2, pincArr3, pincArr4]));
In console.log I am getting an error as follows:
Uncaught TypeError: Cannot read properties of undefined (reading 'length') at possiblecombos
Per line in script it is pointing to the second loop that it cant seem to get the length for pinacrr2 or array2 in function.
What am I doing wrong?
Thanks in advance,
Sandeep