I managed to log each value on a single line, but when I tried using .push() to add each value into an empty array, the result wasn’t what I expected.
Your code so far
const steamrollArray = (sourceArr) => {
let flattenedArr = [];
const isArrayLengthOne = (Arr) => {
if (Arr.length === 1) {
return true;
} else {
return false;
}
};
sourceArr.forEach((element) => {
if (Array.isArray(element) === true) {
// Yes, it is an array.
if (isArrayLengthOne(element) === true) {
// It's an array whose length is one.
steamrollArray(element);
} else {
// It's an array whose length is not one.
steamrollArray(element);
}
} else {
// No, it is not an array.
console.log(element, "No, it is not an array.");
flattenedArr.push(element);
}
});
return flattenedArr;
};
Your browser information:
User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:143.0) Gecko/20100101 Firefox/143.0
Parameters are usually written with lower case (see where you have put “Arr”).
These returns a boolean value - no need to add “=== true”.
Array.isArray(element)
isArrayLengthOne(element)
You have an if and and else statement returning the same code. Why?
You aren’t asked to return any text so remove the console statements.
What do you want your code to do if it is an array? I can’t see that your code is doing anything to an array.
Your code is pushing non arrays to your global variable. If you runt test 4, you can see this but as your code isn’t doing anything with arrays it needs more work.
With this one I suggest you write down what you need your code to do and then build each part.
There are ways of doing it using the skills learned up to this point including those in this chapter. It might be a good idea to have a look online and focus on methods you have learned so far.
I didn’t even think of a non-recursive approach when I did this one: My brain is presently having trouble even imagining how that would work. It’s still Oktoberfest in Munich, I hear; maybe a couple of Maßkrüge would help.
The code you posted is actually on its way to becoming a workable solution. Taking into consideration the things that @a1legalfreelance pointed out, also think about why you even need to think about the array length if you’re going to call the function recursively until it’s no longer an array. So, that bit can go.
Then when you do call the function recursively, what parameter would you need to pass in to retain the nested values? What can you add to your array definition to accommodate that?
Of course, you can still tackle a non-recursive approach, but it’s a bit more painful.
I recently refactored a recursive array-flattening function, replacing .forEach() with .reduce() to make the code more functional and concise. The updated version works perfectly and is easier to read — a small but meaningful improvement!