Steamroller
This is one of the hardest freeCodeCamp challenges so far. It requires a degree of abstract thinking, but when you get your head around what’s actually going on, you’ll see that it’s pretty straightforward.
We need to flatten a nested array whilst accounting for the various degrees of nesting: steamrollArray([1, [2], [3, [[4]]]]) should return [1, 2, 3, 4]. We are given Array.isArray() function as a helpful hint, and it’s pretty self explanatory and determines whether the passed value is an Array.
The first thing we want to do is break arr down into chunks. As an alternative for writing in a for loop, we are going to use a forEach() method to execute a provided function once for each array element.
function steamrollArray(arr) {
arr.forEach(function(element){console.log(element)})
/* logs:
1
[ 2 ]
[ 3, [ [ 4 ] ] ]
*/
}steamrollArray([1, [2], [3, [[4]]]]);
At this stage, you might be able to see that we have a mixture of numbers and array elements.
function steamrollArray(arr) {
arr.forEach(function(element){console.log(typeof(element))})
/* logs:
number
object
object
*/
}steamrollArray([1, [2], [3, [[4]]]]);
We want to filter out any elements which aren’t arrays. To do this, we use Array.isArray() , and will use the push() method to move values into var flat, which is an empty array.
function steamrollArray(arr) {
var flat = [];
arr.forEach(function(element){
if (!Array.isArray(element)){
flat.push(element);
}
});
return flat;// Returns [1]
}steamrollArray([1, [2], [3, [[4]]]]);
We have only returned a single number, which isn’t very good. We need to drill down deeper into the array. At this point, we are going to create a separate function called flatten.
function steamRoller(arr){
var flat = [];
arr.forEach(flatten);
return flat;
function flatten(element){
if (!Array.isArray(element)){
flat.push(element);
}
else{
}
}
}
steamRoller([1, [2], [3], [[4]]]);The reason we create a function called flatten is because we need to make the program recursive. This ensures that every element that fails our Array.isArray test is drilled down until the code finds an element which passes the test.
function steamRoller(arr){
var flat = [];
arr.forEach(flatten);
return flat;
function flatten(element){
if (!Array.isArray(element)){
flat.push(element);
}
else{
element.forEach(flatten);
}
}
}
steamRoller([1, [2], [3], [[4]]]);