3
\$\begingroup\$

I have implemented a solution to flatten an array of multiple levels in Javascript. I am just a newbie so forgive any mistakes. Could someone give me any tips to improve the code?

function streamrollArray(arr) {
    var copyArr = arr;
    var to_return = [];

    while (true) {
        if (copyArr.length <= 0) { return to_return; }
        var head = copyArr[0];
        to_return = to_return.concat(getValues(head));
        //Chop head off since we have got all the values from it.
        copyArr = copyArr.splice(1);
    }
}

function getValues(arr) {
    var copyArr = arr;
    var to_return = [];

    if (!Array.isArray(arr)) {
        return arr;
    }

    while (true) {
        //A head can contain multiples arrays inside it.
        if (copyArr.length <= 0) { return to_return; }
        var head = copyArr[0];
        to_return = to_return.concat(getHead(head));
        copyArr = copyArr.slice(1);
    }
}

function getHead(head) {
    //If its an array we break into it getting the head and keep checking.
    while (Array.isArray(head)) {
        head = head[0];
    }
    return head;
}
\$\endgroup\$
3
\$\begingroup\$

I would think that this might be a problem best solved via recursion.

For example:

function flattenArray(arr) {
    var result = [];

    arr.forEach(function($val) {
        if(Array.isArray($val)) {
            result = result.concat(flattenArray($val));
        } else {
            result.push($val);
        }
    });

    return result;
}

Also consider a more meaningful name for your function like flattenArray vs. steamrollArray. This better conveys what the function does. Look at your question title for example. You used Flattening array to describe your code not Steamrolling array.

\$\endgroup\$
1
  • \$\begingroup\$ sorry streamrollArray is part of freecodecamp algorithms challenges which I am doing. Your right recursion makes the code shorter! \$\endgroup\$
    – dijam
    Mar 2 '17 at 14:47
-2
\$\begingroup\$

I would consider a slight modification of Mike's code to avoid creating so many intermediate arrays:

function flattenArray(arr, outputArray) {
    outputArray ||= [];

    arr.forEach(function($val) {
        if(Array.isArray($val)) {
            flattenArray($val, outputArray));
        } else {
            outputArray.push($val);
        }
    });

    return outputArray;
}
\$\endgroup\$
1
  • \$\begingroup\$ -1 for no explanation at all. \$\endgroup\$
    – t3chb0t
    Mar 2 '17 at 20:55

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.