DEV Community

chandra penugonda
chandra penugonda

Posted on

5

Polyfill Array.flat

A polyfill is a piece of code that provides functionality that's not natively supported by a web browser.

If you're working with a browser that doesn't support the flat() method, you can use a polyfill to provide the same functionality. Here's an example of how you can create a polyfill for the flat() method:

if (!Array.prototype.flat) {
  Array.prototype.flat = function(depth) {
    var flattened = [];

    function flatten(arr, currentDepth) {
      for (var i = 0; i < arr.length; i++) {
        if (Array.isArray(arr[i]) && currentDepth < depth) {
          flatten(arr[i], currentDepth + 1);
        } else {
          flattened.push(arr[i]);
        }
      }
    }

    flatten(this, 0);

    return flattened;
  };
}
Enter fullscreen mode Exit fullscreen mode

The implementation of the flat() method is done recursively. The flatten() function takes an array arr and a current depth currentDepth. If the arr is an array and the currentDepth is less than depth, then the flatten() function is called recursively with the nested array and the currentDepth incremented by 1. Otherwise, the elements of the array are pushed onto the flattened array.

Usage

var nestedArray = [
  [1, 2, 3],
  [4, 5, [6, 7, [8, 9, [10]]]],
  [7, 8, 9],
];

nestedArray.customFlat(2) 

// [ 1, 2, 3, 4, 5, 6, 7, [ 8, 9, [ 10 ] ], 7, 8, 9 ]
Enter fullscreen mode Exit fullscreen mode

Top comments (1)

Collapse
 
narayan_reddy_780f1b923b1 profile image
Narayan Reddy •

Thank you for clean snippet chandra penugonda. It should have default depth values as 1 right to facilitate the flat function if no depth has provided..

SurveyJS custom survey software

JavaScript Form Builder UI Component

Generate dynamic JSON-driven forms directly in your JavaScript app (Angular, React, Vue.js, jQuery) with a fully customizable drag-and-drop form builder. Easily integrate with any backend system and retain full ownership over your data, with no user or form submission limits.

Learn more

đź‘‹ Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay