🌐
npm
npmjs.com › package › array-flat-polyfill
array-flat-polyfill - npm
April 12, 2019 - Array Flat Polyfill is a polyfill for Array.prototype.flat and Array.prototype.flatMap, following the TC39 Proposal.
      » npm install array-flat-polyfill
    
Published   Apr 12, 2019
Version   1.0.1
Author   Jonathan Neal
🌐
GitHub
github.com › jonathantneal › array-flat-polyfill
GitHub - jonathantneal/array-flat-polyfill: A polyfill for Array.prototype.flat and Array.prototype.flatMap · GitHub
Array Flat Polyfill is a polyfill for Array.prototype.flat and Array.prototype.flatMap, following the TC39 Proposal.
Starred by 58 users
Forked by 6 users
Languages   JavaScript
🌐
DEV Community
dev.to › chandrapenugonda › polyfill-arrayflat-3ipb
Polyfill Array.flat - DEV Community
June 4, 2023 - 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; }; }
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Global_Objects › Array › flat
Array.prototype.flat() - JavaScript - MDN Web Docs
The flat() method of Array instances creates a new array with all sub-array elements concatenated into it recursively up to the specified depth.
🌐
Vanillajstoolkit
vanillajstoolkit.com › polyfills › arrayflat
Array.flat() | The Vanilla JS Toolkit
/** * Array.flat() polyfill * Adapted from https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/flat#reduce_concat_isArray_recursivity */ if (!Array.prototype.flat) { Array.prototype.flat = function(depth) { 'use strict'; // If no depth is specified, default to 1 if (depth === undefined) { depth = 1; } // Recursively reduce sub-arrays to the specified depth var flatten = function (arr, depth) { // If depth is 0, return the array as-is if (depth < 1) { return arr.slice(); } // Otherwise, concatenate into the parent array return arr.reduce(function (acc, val) { return acc.concat(Array.isArray(val) ?
🌐
GitHub
github.com › es-shims › Array.prototype.flat
GitHub - es-shims/Array.prototype.flat: An ESnext spec-compliant `Array.prototype.flat` shim/polyfill/replacement that works as far down as ES3.
var flat = require('array.prototype.flat'); var assert = require('assert'); /* when Array#flat is not present */ delete Array.prototype.flat; var shimmedFlat = flat.shim(); assert.equal(shimmedFlat, flat.getPolyfill()); assert.deepEqual(arr.flat(), ...
Starred by 31 users
Forked by 8 users
Languages   JavaScript 100.0% | JavaScript 100.0%
🌐
Medium
medium.com › @rano3003 › javascript-interview-question-polyfill-to-flatten-an-array-a9066c8c77d0
Javascript Interview Question: Polyfill to flatten an Array | by Poonam | Medium
June 29, 2023 - Because we have to create polyfill for flatten which is an Array method we will have to add it to the prototype of Array so that it will be available for all the arrays in javascript like how we have map filter reduced method available as array methods.
🌐
DEV Community
dev.to › dhrn › day-3-polyfill-for-arrayflat-2464
Day 3: Polyfill for Array.flat() - DEV Community
July 12, 2023 - // Check if Array.prototype.myFlat exists if (!Array.prototype.myFlat) { Array.prototype.myFlat = function (depth = 1) { // Function to flatten the array recursively const flatten = (arr, currentDepth) => { // Base case: depth reached or array is not an array if (currentDepth === 0 || !Array.isArray(arr)) { return arr; } // Recursive case: flatten each element in the array return arr.reduce((result, element) => { if (Array.isArray(element)) { return result.concat(flatten(element, currentDepth - 1)); } return result.concat(element); }, []); }; return flatten(this, depth); }; } // Test cases const array = [1, [2], [3, [3]]]; console.log(array.myFlat()); // Output: [1, 2, 3, [3]] console.log(array.myFlat(1)); // Output: [1, 2, 3, [3]] console.log(array.myFlat(3)); // Output: [1, 2, 3, 3] console.log(array.myFlat(Infinity)); // Output: [1, 2, 3, 3]
🌐
OneCompiler
onecompiler.com › javascript › 3w9djra3k
Javascript Array Flatten Polyfill - JavaScript - OneCompiler
var flatten = a => Array.isArray(a) ? [].concat(...a.map(flatten)) : a; var deepFlatten = (arr, depth = 1) => { return depth > 0 ? arr.reduce((acc, val) => acc.concat(Array.isArray(val) ?
Find elsewhere
🌐
YouTube
youtube.com › watch
Flattening an array in JS (array.flat() polyfill). - YouTube
In this video, we take a look at how to recreate the "array.flat" method in javascript. This polyfill is again a very common question that's asked in intervi...
Published   May 16, 2024
Top answer
1 of 16
76

Perfect use case for recursion, which could handle even deeper structure:

function flatten(ary) {
    var ret = [];
    for(var i = 0; i < ary.length; i++) {
        if(Array.isArray(ary[i])) {
            ret = ret.concat(flatten(ary[i]));
        } else {
            ret.push(ary[i]);
        }
    }
    return ret;
}

flatten([[[[[0]], [1]], [[[2], [3]]], [[4], [5]]]]) // [0, 1, 2, 3, 4, 5]

Alternatively, as an Array method:

Array.prototype.flatten = function() {
    var ret = [];
    for(var i = 0; i < this.length; i++) {
        if(Array.isArray(this[i])) {
            ret = ret.concat(this[i].flatten());
        } else {
            ret.push(this[i]);
        }
    }
    return ret;
};

[[[[[0]], [1]], [[[2], [3]]], [[4], [5]]]].flatten() // [0, 1, 2, 3, 4, 5]

EDIT #1: Well, think it a little bit functional way (except for the named recursion which should be using Y-combinator for pure functional :D).

function flatten(ary) {
  return ary.reduce(function(a, b) {
    if (Array.isArray(b)) {
      return a.concat(flatten(b))
    }
    return a.concat(b)
  }, [])
}

Let's adopt some ES6 syntax which makes it even shorter, in one line.

const flatten = (ary) => ary.reduce((a, b) => a.concat(Array.isArray(b) ? flatten(b) : b), [])

But remember, this one cannot be applied as an array method, because arrow functions don't have theirs own this.


EDIT #2: With the latest Array.prototype.flat proposal this is super easy. The array method accepts an optional parameter depth, which specifies how deep a nested array structure should be flattened (default to 1).

[[[[[0]], [1]], [[[2], [3]]], [[4], [5]]]].flat()  // [[[[0]], [1]], [[[2], [3]]], [[4], [5]]]
[[[[[0]], [1]], [[[2], [3]]], [[4], [5]]]].flat(2) // [[[0]], [1], [[2], [3]], [4], [5]]
[[[[[0]], [1]], [[[2], [3]]], [[4], [5]]]].flat(3) // [[0], 1, [2], [3], 4, 5]
[[[[[0]], [1]], [[[2], [3]]], [[4], [5]]]].flat(4) // [0, 1, 2, 3, 4, 5]

So to flatten an array of arbitrary depth, just call flat method with Infinity.

[[[[[0]], [1]], [[[2], [3]]], [[4], [5]]]].flat(Infinity) // [0, 1, 2, 3, 4, 5]
2 of 16
53

ES6-style with recursion:

Redacted

June 2018 Update:

There is now an ES proposal for an Array.prototype.flat method. It is currently at stage 3, meaning it's likely to be implemented by browsers soon(ish) and make it into the spec in its current form. There are probably some polyfills floating around.

Example:

const nested = [[[0], [1]], [[2], [3]], [[4], [5]]];
const flattened = nested.flat(2);  // Need to specify depth if > 1

June 2019 Update:

Array.prototype.flat was officially added to the language in the ES2019 spec.

🌐
CodeSandbox
codesandbox.io › s › implement-a-polyfill-for-arrayprototypeflat-t6qbh
Implement a polyfill for Array.prototype.flat - CodeSandbox
April 24, 2021 - Implement a polyfill for Array.prototype.flat by nandwana92 using parcel-bundler
Published   Apr 24, 2021
Author   nandwana92
🌐
GitHub
github.com › jonathantneal › array-flat-polyfill › blob › master › src › flat.js
array-flat-polyfill/src/flat.js at master · jonathantneal/array-flat-polyfill
A polyfill for Array.prototype.flat and Array.prototype.flatMap - array-flat-polyfill/src/flat.js at master · jonathantneal/array-flat-polyfill
Author   jonathantneal
🌐
CodeSandbox
codesandbox.io › examples › package › array-flat-polyfill
array-flat-polyfill examples - CodeSandbox
Use this online array-flat-polyfill playground to view and fork array-flat-polyfill example apps and templates on CodeSandbox.
🌐
Medium
medium.com › geekculture › solve-meta-amazon-google-apple-interview-question-write-custom-implementation-for-array-flat-8e0072961c29
Solve Meta | Amazon | Google | Apple Interview Question. Write custom implementation for Array.flat() | by Vasanth Bhat | Geek Culture | Medium
October 21, 2022 - You can straightaway goto below video and watch my explanation. Otherwise You can also read the article. ... The flat() method creates a new array with all sub-array elements concatenated into it recursively up to the specified depth.
🌐
CodePen
codepen.io › chungguo › pen › xvXeMR
array flat polyfill
acc.concat(flat(cur)) : acc.concat(cur); }, []); } console.log(flat([1, 3, [2, 4, [193, 3, [12]]]])); function flatten (arr) { let stack = [ ...arr ]; let res = []; while (stack.length) { let node = stack.pop(); if (Array.isArray(node)) { stack = [ ...stack, ...node ]; } else { res.push(node); } } return res; } console.log('flatten', flatten([1, 3, [2, 4, [193, 3, [12]]]]));
🌐
Stackademic
blog.stackademic.com › from-nested-to-flat-implementing-polyfill-for-array-flat-in-javascript-d4a8f87241fc
From Nested to Flat: Implementing Polyfill for Array.flat() in JavaScript | by Mansi Manhas | Stackademic
August 3, 2024 - Array.prototype.flatArrayRecursively = function() { const result = []; for (let element of this) { if (Array.isArray(element)) { result.push(...element.flatArrayRecursively()); } else { result.push(element); } } return result; } /* const myArray = [1, 2, [3, [4, [5]]]] console.log(myArray.flatArrayRecursively()); */ The above polyfill recursively processes each element in the input array.
🌐
GitHub
gist.github.com › 50364079cf0390a73e745e513fa912d9
140b polyfill for Array.prototype.flat() and Array.prototype.flatMap(). https://npm.im/tiny-array-flat-polyfill · GitHub
import 'tiny-array-flat-polyfill'; const ARR = [1, [2, [3]], [[[4]]], 5] ARR.flat() // [1, 2, [3], [[4]], 5] ARR.flat(4) // [1, 2, 3, 4, 5] [[1,2],[3,4]].flatMap(([x,y])=>x+y) // [3,7]
🌐
Libraries.io
libraries.io › npm › array-flat-polyfill
array-flat-polyfill 1.0.1 on npm - Libraries.io
Array Flat Polyfill is a polyfill for Array.prototype.flat and Array.prototype.flatMap, following the TC39 Proposal.
🌐
Npm
npm.io › package › array-flat-polyfill
Array-flat-polyfill NPM | npm.io
Array Flat Polyfill is a polyfill for Array.prototype.flat and Array.prototype.flatMap, following the TC39 Proposal.