k.chan k.chan - 7 months ago 21
Javascript Question

How can I reset the global variable after calling the function?

I've written a function with recursive approach to get the values from nested Array.
The problem is, I can't reset the global variable after each call. Here after every call the results are being appended to previous result instead of giving new result. I know, Global variable isn't being reset, so data will always append. But I can't define the variable inside the function as its recursive call.

How can I avoid this situation? Any help would be appreciated.

var res = [];
function getData(arr) {
if(!Array.isArray(arr)) {
res.push(arr);
return res;
}
for(var i = 0; i < arr.length; i++) {
getData(arr[i]);
}
return res;
}

getData([1, [2], [3, [[4]]]]); // res = [1, 2, 3, 4]
getData([[["a"]], [["b"]]]); // res = [1, 2, 3, 4, "a", "b"], expected is res = ["a", "b"];
getData([1, {}, [3, [[4]]]]);

Answer

But I can't define the variable inside the function as its recursive call.

You can define the result variable inside the function but you need to properly deal with the return values of your recursive calls:

function getData(arr) {
    var res = [];

    if (Array.isArray(arr)) {
        for (var i = 0; i < arr.length; i++) {
            res = res.concat(getData(arr[i]));
        }
    } else {
        res.push(arr);
    }

    return res;
}

(And you don't need to make the result array a parameter of the function.)