Flatten an array of arbitrarily nested arrays of integers Write a piece of functioning code that will flatten an array of arbitrarily nested arrays of integers into a flat array of integers. e.g. [[1,2,[3]],4] -> [1,2,3,4].


* tests use Jasmine can be found  http://jsbin.com/harofo/4/edit?html,js,output
* @input  array
* @output array
*/

function flatten(arr) {
    // this function is called in recursion mode
    let result = [];
    if (arr &amp;&amp; arr.length &gt; 0) {
        arr.forEach(function(value) {
            if(Array.isArray(value)) {
                result = result.concat(flatten(value));
            } else {
                result.push(value);
            }
        });
    }    
    return result;

};
The check for arr.length &gt; 0 is not needed: forEach() can be called
on an empty array (and does nothing in that case).

The check if (arr) protects against a call with an undefined argument,
but not against a call with a non-array. As an example, flatten(123)
would cause a JavaScript error. So you have to decide:


If the argument to flatten() is known to be an array then the
outer if statement is not needed at all.
If flatten() can be called with any argument than you need to check
for an array before calling forEach().


See also Flatten an array on how reduce() can be used instead of a loop.