To build off of Daphoque's answer (which is equivalent to flat(Infinity), I believe), you could do a full polyfill like this.
if (!Array.prototype.flat) {
Array.prototype.flat = function (maxDepth, currentDepth) {
"use strict";
var array = this;
maxDepth = maxDepth === Infinity
? Number.MAX_SAFE_INTEGER
: parseInt(maxDepth, 10) || 1;
currentDepth = parseInt(currentDepth, 10) || 0;
// It's not an array or it's an empty array, return the object.
if (!Array.isArray(array) || !array.length) {
return array;
}
// If the first element is itself an array and we're not at maxDepth,
// flatten it with a recursive call first.
// If the first element is not an array, an array with just that element IS the
// flattened representation.
// **Edge case**: If the first element is an empty element/an "array hole", skip it.
// (see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/flat#Examples)
var firstElemFlattened = (Array.isArray(array[0]) && currentDepth < maxDepth)
? array[0].flat(maxDepth, currentDepth + 1)
: array[0] === undefined ? [] : [array[0]];
return firstElemFlattened.concat(array.slice(1).flat(maxDepth, currentDepth));
};
}
And here are some poorly named Jasmine tests based on the examples on the MDN page:
// MDN examples:
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/flat#Examples
describe('testing flatmap against mdn examples', function () {
"use strict";
// loadFolders,
it('works 1', function () {
var arr1 = [1, 2, [3, 4]];
var out = arr1.flat();
expect(out).toEqual([1, 2, 3, 4]);
});
it('works 2', function () {
var arr2 = [1, 2, [3, 4, [5, 6]]];
var out2 = arr2.flat();
expect(out2).toEqual([1, 2, 3, 4, [5, 6]]);
});
it('works 3', function () {
var arr3 = [1, 2, [3, 4, [5, 6]]];
var out3 = arr3.flat(2);
expect(out3).toEqual([1, 2, 3, 4, 5, 6]);
});
it('works 4', function () {
var arr4 = [1, 2, [3, 4, [5, 6, [7, 8, [9, 10]]]]];
var out4 = arr4.flat(Infinity);
expect(out4).toEqual([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
});
it('works 5', function () {
var arr5 = [1, 2, , 4, 5];
var out5 = arr5.flat();
expect(out5).toEqual([1, 2, 4, 5]);
});
it('works 6', function () {
var arr6 = [1, 2, , 4, [5, 6]];
var out6 = arr6.flat();
expect(out6).toEqual([1, 2, 4, 5, 6]);
});
});
I'm surprised that I didn't find a polyfill for flat on MDN like they have for, eg, map, but this one does seem to pass the examples there.
Let me know if I've missed a case.