[ES2019] Use JavaScript ES2019 flatMap to Map and Filter an Array
ES2019 introduces the Array.prototype.flatMap method. In this lesson, we'll investigate a common use case for mapping and filtering an array in a single iteration. We'll then see how to do this using Array.prototype.reduce, and then refactor the code to do the same thing using the ES2019 .flatMap method.
Let's recap what we know about .filter and .map in JS.
For .filter:
We can choose to include or exclude one element from the original array, but we cannot apply transform function to the item.
For .map:
We can apply transform function to the element but we cannot exclude the element from the array.
const data = [{a: 1, b: 2, c: 100}, {a: 13, b: 22, c: 200}, {a: 10, b: 200, c: 99}] function getABWhereCLargerThan100 (data) { return data.flatMap(o => o.c >= 100 ? [o.a, o.b]: []) } console.log(getABWhereCLargerThan100(data)); //[1, 2, 13, 22]
If inside .flatMap we return [], it is the same as filtering current element from the array.
So if we want to apply transform function and also at the same time filter out some elements, we can use .flatMap from ES2019:
相关文章
- JavaScript获取DOM节点
- LINQ to JavaScript
- [Javascript] Wait for Multiple JavaScript Promises to Settle with Promise.allSettled()
- [Javascript] Creating an Iterator from an Array
- [Javascript] Link to Other Objects through the JavaScript Prototype Chain
- JavaScript RegExp Object 正则表达式入门
- [Javascript] Destructuring array by using object syntax
- [Javascript] Natively Format JavaScript Dates and Times
- [Javascript] Wait for the Fastest JavaScript Promise to Be Fulfilled with Promise.any()
- [Javascript] Wait for Multiple JavaScript Promises to Settle with Promise.allSettled()
- [Javascript] Hide Properties from Showing Up in "for ... in" Loops in JavaScript
- [ES2019] Use JavaScript ES2019 flatMap to Map and Filter an Array
- [Javascript] Conditionally spread entries to a JavaScript object
- [Javascript] Link to Other Objects through the JavaScript Prototype Chain
- [Javascript] Decorators in JavaScript
- [Javascript] Modifying an Immutable.js Map()
- JavaScript Source Map 详解
- 一个百度贴吧下载指定单个帖子所有回复的工具(JavaScript)实现
- 如何使用 Chrome 开发者工具 Performance tab 分析 JavaScript 的执行瓶颈
- rxjs里subscribeToArray的一个JavaScript模拟实现
- javascript知识点
- [手游项目3]-9-Go语言sync.Map(在并发环境中使用的map)
- Map生成器 map适配器如今能够使用各种不同的Generator,iterator和常量值的组合来填充Map初始化对象
- Dart基础第6篇:集合类型List Set Map详解 以及循环语句 forEach map where any every
- web前端框架Javascript开发基础之JavaScript作用域