Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning an Array in JavaScript

I was inspired by this question to write a recursive function in JavaScript to add elements of an array and return an array accordingly.

in Pseudocode

arr = [1,2,3,4,5,6]
func (arr,2) = > [1+3+5, 2+4+6]
                 [9,12]
func (arr,3) = > [1+4,2+5,3+6]
                 [5,7,9]

So I wrote a fiddle, here.

var input = [1,2,3,4,5,6,7,8,9];

function tupleAdd(tuple,i,p,t,output){
    if(typeof t == "undefined")
        t=0;
    if(typeof p == "undefined")
        p=0;
    if(typeof output == "undefined")
        output = [];
    if(typeof output[t] =="undefined")
        output[t]=0;

    output[t]+=i[p];
    p++;
    t++;
    t>=tuple?t=0:null;
    if(p<i.length)
        tupleAdd(tuple,i,p,t,output);
    else{
        console.log(output);
        return(output);
    }
}

x = tupleAdd(3,input);
console.log(x);

My function works, as the first console.log() shows the appropriate values. What weirds me out is that when I return output (with or without parens), and try and log it again, I get undefined.

I find this deeply unsettling. Can anyone shed some light on why the return value is different than the console.log value?

like image 340
Jason Nichols Avatar asked May 29 '26 16:05

Jason Nichols


1 Answers

Your recursion is broken. You are getting undefined since you do not have a return on the function call inside.

tupleAdd(tuple,i,p,t,output);

needs to be

return tupleAdd(tuple,i,p,t,output);
like image 130
epascarello Avatar answered Jun 01 '26 06:06

epascarello



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!