How to flatten array using javascript

 

It's a common question asked during the interview process as well as many times required in day to day projects.

Let's go through the code to flatten an array recursively using javascript.

 

const flattenArray = arr => {
    const result = [];

    const flatten = arr => {
        arr.forEach(element => {
            if(Array.isArray(element)){
                 flatten(element);
            }else{
                result.push(element);
            }
        });
    }

    flatten(arr);
    return result;
}

module.exports = flattenArray

 

Above javascript uses es6 arrow function and #6 used a javascript utility function to check if the passed argument is a nested array or a value.

If the argument passed is array we recursively pass the argument again to the function untill a value is encountered. Finally the value is pushed to an array and returned.