I’ve just completed the Steamroller challenge from the JavaScript intermediate algorithms section and I’m pretty pumped. I was wondering if someone could answer a couple of questions about my code.
The challenge was to “flatten” all the items of an array of nested arrays into an array with only one depth. My solution (find below) was to cycle through the main array and check if each item was an array. If not, push it to a new arra (flatArr). If it was an array, cycle through it by calling the same function I used to cycle through the main one recursively (still pretty psyched I got it to work).
I have two question regarding my solution:
(1) I used a function within a function to avoid redeclaring my flatArr variable with each recursive iteration. Can you think of a way I could have avoided this and just used one single function?
(2) To avoid confusion, I used the same names for the function parameters and corresponding variables in each function throughout. In tutorials, I’ve noticed that function parameters usually have different names than the items that are passed. Is there a reason for this?
(3) Any other commentary/criticism would be appreciated.
function steamrollArray(arr) {
let flatArr = [];
// Cycles through at array and pushes things that aren't arrays to new array
function cycleThrough(arr, flatArr) {
for (let i = 0; i < arr.length; i++) {
// If item is an array, cycle through it. Must be done recursively.
if (Array.isArray(arr[i])) {
// Recusively cycle through
cycleThrough(arr[i], flatArr)
// If not an array, push to new array
} else {
flatArr.push(arr[i]);
}
}
return flatArr;
}
return cycleThrough(arr, flatArr);
}