I am stumped as to why I am getting the error because I am passing in an array that is defined and should have length. Yet, I keep getting the "Type Error on line XXX: Cannot read properties of undefined (reading 'length')"
Here is the code I am working on...
function getAllCombos(arr) {
// declare an array to hold results
let results = [];
// declare an innerfunction which takes a prefix and the original array passed in
function recurse(prefix, arr) {
// loop through the original array, our base case will be when the loop ends
for (let i = 0; i < arr.length; i++) {
// push the results of spreading the prefix into an array along with the current element both in an array
results.push([...prefix, arr[i]]);
// recursive case: now we build the prefix, we recurse and pass into our prefix parameter an array consisting of the prefix spread in, the current element being iterated on, and the original array sliced after our current element
recurse([...prefix, arr[i], arr.slice(i+1)])
}
}
// call the inner function with an empry prefix argument and the original array
recurse([], arr);
// return the results array
return results;
}
and here are some test cases...
console.log(getAllCombos(['a', 'b'])); // -> [['a','b'], ['a'], ['b'], []]
console.log(getAllCombos(['a', 'b', 'c']));
// -> [
// ['a', 'b', 'c'],
// ['a', 'b'],
// ['a', 'c'],
// ['a'],
// ['b', 'c'],
// ['b'],
// ['c'],
// [],
// ]
Can someone please explain to me why I keep getting this error message even though I am passing in an array that has length?
Thank you for any pointers!