Stem roller : almost there but

Stem roller : almost there but
0

#1

Hello,

Does anybody have an idea of what is wrong in the code below?
When the testArray returns a number, it switches to undefined as you can see in the console.

function steamrollArray(arr) {
var newArr=[];

	function testArray(a){
			if (Array.isArray(a)){
			for(var j=0;j<a.length;j++){
			testArray(a[j]);
			}
		}else{
		console.log(a);
		console.log(typeof(a));
		return a;
		}
	}

	for (var i=0;i<arr.length;i++){
		newArr.push(testArray(arr[i]));
	}

 
  return newArr;
}

steamrollArray([1, [2], [3, [[4]]]]);

CONSOLE
/* 1 /
/
number /
/
2 /
/
number /
/
3 /
/
number /
/
4 /
/
number */
Résultat :
[1, undefined, undefined]

Thanks

Julien


#2

What exactly are you trying to accomplish with the following line of code?

		for(var j=0;j<a.length;j++){
		 	testArray(a[j]);
		}

#3

Thank you for your reply.

Each times it meets an array it needs to go through the entire array to check if there is any other array. If the first element of the array is also an array, it will go through this array again until it finds a number and will return it.


#4

Thank you!! Your question made me understand, i just added return and it almost works. I still do not understand why it doesn’t return the 4

function steamrollArray(arr) {
var newArr=[];

	function testArray(a){
			if (Array.isArray(a)){
			for(var j=0;j<a.length;j++){
			return testArray(a[j]);
			}
		}else{
		console.log(a);
		console.log(typeof(a));
		return a;
		}
	}

	for (var i=0;i<arr.length;i++){
		newArr.push(testArray(arr[i]));
	}

 
  return newArr;
}

steamrollArray([1, [2], [3, [[4]]]]);

```
CONSOLE

/* 1 */
/* number */
/* 2 */
/* number */
/* 3 */
/* number */
Résultat :
[1, 2, 3]

#5

fix the function call like this steamrollArray([1, 2, 3, 4]);


#6

I took out your console.logs and added a couple new ones to your code. See if this helps you understand why it never gets to the embedded 4.

function steamrollArray(arr) {
    var newArr=[];
    function testArray(a){
        console.log(a, Array.isArray(a) ? 'is array' : 'is not array');
        if (Array.isArray(a)){
            console.log('a.length='+a.length);
            for(var j=0;j<a.length;j++) {
               return testArray(a[j]);
            }
       }
       else {return a;}
    }
    for (var i=0;i<arr.length;i++){
        newArr.push(testArray(arr[i]));
    }
    return newArr;
}

steamrollArray([1, [2], [3, [[4]]]]);

#7

Thanks for your help. I finally managed to solve the problem. It would return a number and end the function testArray before going through the array.
I add to newArr.push in the function itself.


function steamrollArray(arr) {
var newArr=[];


	function testArray(a){
	var j=0;	
			
		if (Array.isArray(a)){
			for(var j=0;j<a.length;j++){
			testArray(a[j]);	
			}
		}else {
		newArr.push(a);	
		}
	}
		
	
	for (var i=0;i<arr.length;i++){
						
						console.log("testArray:"+testArray(arr[i]));
	
	}

 
  return newArr;
}