Steamroller trouble

Intermediate challenge, Steamroller

Ive worked on this challenge a few times, with different strategies like recursive (still dont understand it)
and today i used .flat() which doesnt really work … for example .flat(Infinity);

Also here is the guide for reference
https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/steamroller

Any advice is welcome

function steamrollArray(arr) {
	let newarr = [...arr].flat();
	//console.log(newarr);
	let notarr = [];
	newarr.map(e => {
		//console.log(e, Array.isArray(e));
		if (Number(e) == e) {
			notarr.push(e);
		} else if (Array.isArray(e)) {
			console.log("we got an array here");
			notarr.concat(e);
		}
		//else if(!Array.isArray(e)){
		else {
			notarr.concat(e);
		}
	}); //map
	console.log(notarr.flat());
	return notarr.flat();
} //function
steamrollArray([1, [2],[3, [[4]]]]);

Hello tommy.

As a quick-fix, JavaScript’s flat method accepts an array in the form of a number to describe the depth at which you would like to flatten. So…

return arr.flat([Infinity]); // Works

Hope this helps.

1 Like

FYI - We are in the process of changing this challenge to no longer allowing the flat method in the solution, since it defeats to purpose of solving the challenge with an algorithm.

1 Like

Ah I see I was missing the array brackets within the method
Yikes that was the whole solution!

@RandellDawson thats gonna be one hell of a challenge without using that filter method :laughing:

Would this include the flatmap() method??

This is one of those classic recursive algorithms every programmer should know, so restricting .flat() makes total sense. I would really suggest to try to solve it recursively, it’s quite far from “hell”.

I liked it easy to implement using recursion

flatMap() should be restricted not only from the challenge but also from existence :laughing:

It kinda reminds about the times when JS was like this: "hello, world".blink(). If .reduce(), .filter() and other HOF methods where people they would definitely come to Ecma office with “WFT” faces…

lol what are you talking about… also whats the best way to learn recursion… its giving me a headache!!

First step to understand recursion is to understand precedence. Function call has very high precedence, it means that result of the function will be calculated before almost anything else. So, when you have something like this in your code:

return func();

JS will first compute result of the func() and then return it.

1 Like

I just realized but this part of the code never actually ran… @Sky020

 else if (Array.isArray(e)) {
			console.log("we got an array here");
			notarr.concat(e);