zoukankan      html  css  js  c++  java
  • [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:

  • 相关阅读:
    BlockingQueue(阻塞队列)详解
    异步远程调用线程池队列
    JVM中的五大内存区域划分详解及快速扫盲
    http链接管理器
    influxDB 增加
    ArcGIS的sde数据库连接
    arcgis server注册文件夹
    arcmap编辑oracle数据库
    create database connection
    发布gp服务失败
  • 原文地址:https://www.cnblogs.com/Answer1215/p/11237807.html
Copyright © 2011-2022 走看看