[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_JavaScript走向成熟
- 【说站】JavaScript使用map创建新数组
- asp还有人用吗_javascript和jsp区别
- 用javascript分类刷leetcode--位运算(图文视频讲解)
- js 怎么使用正则表达式-理解Javascript的正则表达式
- Javascript DOM(一)
- JavaScript黑科技:隐秘执行
- JavaScript 模仿Java的Map集合,实现功能详解编程语言
- JavaScript学习总结(二十)——Javascript非构造函数的继承详解编程语言
- JavaScript学习总结(九)——Javascript面向(基于)对象编程详解编程语言
- javascript添加到收藏夹写法详解编程语言
- Redis精准读取Map数据的窍门(redis获取map)
- 使用Redis轻松操作Map数据结构(redis操作map)
- Oracle中Map结构的精妙运用(oracle中MAP结构)
- Javascript常用运算符(Operators)-javascript基础教程
- 浅谈Javascript嵌套函数及闭包
- javaScript计算两个日期的天数相差(示例代码)
- javascript二维数组转置实例