JavaScript Recursion Exercise

Flatten

Create a function that flattens all nested arrays in the given array.

My initial instinct was to use the JavaScript function .flat() and recursion. However, a problem occurred with the base case. In order for recursion to function correctly, the base case needs to be set to determine if the recursion should stop. In my above solution, I wanted to compare the array before and after flattening it. I then realized that arrays as a whole could not be compared. In order to compare two different arrays, all the elements should be compared one-by-one. Since the base case is triggered on every cycle of the recursion, this meant that the array would be looped for its entire length on every recursion. So a no-no.

After a light research, the ideal solution I came up with was simply checking if every element of the array was an array or not. If it’s an array, it will call the function itself with the first element. Only if the first element of the array is not an array, it will be pushed to the answer string, and the initial array would be sliced from the second element to be put into the recursive function again.

const flatten = (arr) => {
    if (arr.length === 0) return [];
    let newArr = [];

    if(Array.isArray(arr[0])) {
        newArr = flatten(arr[0]);
    } else {
        newArr.push(arr[0])
    }
    return newArr.concat(flatten(arr.slice(1)));
};

Stringify Numbers

In an object, with possible nested objects, change all of numbers into strings, including those in the nested objects.

Although the task was pretty straight forward, my challenge was to sort out arrays, and return them as it was as arrays instead of changing the to objects. This was because when running typeof in JavaScript, arrays also return object. My solution was to check specifically for arrays with Array.isArray() function.

const stringifyNumbers = (obj) => {
    const newObj = {};
    if(Array.isArray(obj)) return obj;
    for (let p in obj) {
        (typeof(obj[p]) === 'number' ? newObj[p] = obj[p].toString() : typeof(obj[p]) === 'object' ? newObj[p] = stringifyNumbers(obj[p]) : newObj[p] = obj[p]);
    }
    return newObj;
};

let obj = {
    num: 1,
    test: [],
    data: {
        val: 4,
        info: {
            isRight: true,
            random: 66
        }
    }
}

stringifyNumbers(obj)