Javascript Array.flat

We will discuss Polyfill for Array.flat().

About

Array.flat is a function that will take depth as a parameter and return new array of concatenated arrays till depth.

const array = [1,3,4,5,[2,3,4,[5,67]], [1,2,3]]
console.log(array.flat())
// [ 1, 3, 4, 5, 2, 3, 4, [ 5, 67 ], 1, 2, 3 ]
console.log(array.flat(2))
//[
//  1, 3, 4,  5, 2,
//  3, 4, 5, 67, 1,
//  2, 3
//]
console.log(array.flat(6))
//[
//  1, 3, 4,  5, 2,
//  3, 4, 5, 67, 1,
//  2, 3
//]

Polyfill

  1. Return new array.

  2. Take depth as the parameter.

  3. Check if the element is an array.

  4. Concatenate all the sub-arrays to depth

Array.prototype.customFlat = function(depth){
 let flatArr = []
 if(!Array.isArray(this)){
  return Exception(`${this}.customFlat is not function`)
 }
 if(depth == 0 ){
    return this
 }
 this.forEach( item => {
   if(Array.isArray(item)){
     flatArr.push(...item.customFlat(depth-1))
   }else{
    flatArr.push(item)
   }
 })
 return flatArr
}

Here we are using recursion to reach to array at a given depth for each array element.

If we pass very big number as depth it will only go to element at maximum depth after that it will not call same function recursively

// Sample output
console.log(array.customFlat())
// [ 1, 3, 4, 5, 2, 3, 4, [ 5, 67 ], 1, 2, 3 ]
console.log(array.customFlat(2))
//[
//  1, 3, 4,  5, 2,
//  3, 4, 5, 67, 1,
//  2, 3
//]

Hit ❤️ to encourage me to add more Polyfills.