What is array.prototype.flatmap?
The array.prototype.flatmap package provides a polyfill for the flatMap method that was added to the Array prototype in ECMAScript 2019. This method allows you to map over an array and flatten the result by one level in a single operation. It is particularly useful for dealing with arrays of arrays or when applying a function that returns an array for each element.
What are array.prototype.flatmap's main functionalities?
Mapping and Flattening
This code demonstrates how to use flatMap to map over an array of arrays, doubling each element, and then flattening the result into a single array. The output would be [2, 4, 6, 8].
[[1, 2], [3, 4]].flatMap(x => x.map(y => y * 2))
Filtering and Mapping in One Step
This example shows how flatMap can be used to filter and map over an array simultaneously. It doubles the even numbers and removes the odd numbers, resulting in [4, 8].
[1, 2, 3, 4].flatMap(x => x % 2 === 0 ? [x * 2] : [])
Other packages similar to array.prototype.flatmap
lodash.flatten
Lodash's flatten method provides similar functionality to flatMap for flattening arrays, but it does not include mapping. You would need to chain it with map for similar effects, making array.prototype.flatmap more convenient for combined operations.
underscore.js
Underscore.js offers methods like _.flatten and _.map which can be combined to achieve similar results to flatMap. However, like lodash, this requires chaining multiple operations, whereas array.prototype.flatmap integrates both into one method.
array.prototype.flatmap
An ES2019 spec-compliant Array.prototype.flatMap
shim/polyfill/replacement that works as far down as ES3.
This package implements the es-shim API interface. It works in an ES3-supported environment and complies with the spec.
Because Array.prototype.flatMap
depends on a receiver (the this
value), the main export takes the array to operate on as the first argument.
Getting started
npm install --save array.prototype.flatmap
Usage/Examples
var flatMap = require('array.prototype.flatmap');
var assert = require('assert');
var arr = [1, [2], [], 3];
var results = flatMap(arr, function (x, i) {
assert.equal(x, arr[i]);
return x;
});
assert.deepEqual(results, [1, 2, 3]);
var flatMap = require('array.prototype.flatmap');
var assert = require('assert');
delete Array.prototype.flatMap;
var shimmedFlatMap = flatMap.shim();
var mapper = function (x) { return [x, 1]; };
assert.equal(shimmedFlatMap, flatMap.getPolyfill());
assert.deepEqual(arr.flatMap(mapper), flatMap(arr, mapper));
var flatMap = require('array.prototype.flatmap');
var assert = require('assert');
var shimmedIncludes = flatMap.shim();
var mapper = function (x) { return [x, 1]; };
assert.equal(shimmedIncludes, Array.prototype.flatMap);
assert.deepEqual(arr.flatMap(mapper), flatMap(arr, mapper));
Tests
Simply clone the repo, npm install
, and run npm test