Support my work ♥

JavaScript Array.prototype.flatMap Polyfill

flatMap method is identical to a map followed by a call to flat of depth 1.

This polyfill enables the function on Internet Explorer and some mobile browsers.

// BEGIN polyfill_flatMap
if (!Array.prototype.flatMap) {
    Object.defineProperty(Array.prototype, 'flatMap', {
        value: function(callback, thisArg) {
            var self = thisArg || this;
            if (self === null) {
                throw new TypeError( 'Array.prototype.flatMap ' +
                'called on null or undefined' );
            }
            if (typeof callback !== 'function') {
                throw new TypeError( callback +
                ' is not a function');
            }

            var list = [];

            // 1. Let O be ? ToObject(this value).
            var o = Object(self);

            // 2. Let len be ? ToLength(? Get(O, "length")).
            var len = o.length >>> 0;

            for (var k = 0; k < len; ++k) {
                if (k in o) {
                    var part_list = callback.call(self, o[k], k, o);
                    list = list.concat(part_list);
                }
            }

            return list;
        }
    });
}
// END polyfill_flatMap

Example

After loading the polyfill this code works on all browsers:

var nested_list = [ 1, 2, [3, 4], 5, 6 ];

// testing for the length field
var flat_list = nested_list.flatMap(x => x.length ? x : [x]);
// Array(6) [ 1, 2, 3, 4, 5, 6 ]

links

social