Flatten an array Completely

 const arr = [1, 2, 3, [4, 5, 6], [7, 8, [9, 10, 11], 12], [13, 14, 15]]

  var flat = function (arr, n) {

    // return arr.flat(n)

    let modifiedArr=arr;

    for(let i =0 ;i <n ;i++){

    let output=modifiedArr.reduce((acc,curr)=>{

        if(Array.isArray(curr)){

            return [...acc,...curr];

        }

        else{

          return [...acc,curr]

        }     

        return acc;

        },[])

    modifiedArr=output;

    }

return modifiedArr;

};

console.log(flat(arr,0))


var flat = function(arr) {

  let modifiedArr = [];


  arr.forEach((item) => {

    if (Array.isArray(item)) {

      modifiedArr.push(...flat(item)); // Recursively flatten nested arrays

    } else {

      modifiedArr.push(item);

    }

  });


  return modifiedArr;

};


const arr = [[1], 2, 3, [4, [5], 6], [7, 8, [9, 10, 11], 12], [13, 14, 15]];

console.log(flat(arr));

Comments

Popular posts from this blog

TO the new

4048