zoukankan      html  css  js  c++  java
  • [Javascript] Advanced Reduce: Flatten, Flatmap and ReduceRight

    Learn a few advanced reduction patterns: flatten allows you to merge a set of arrays into a single array, the dreaded flatmap allows you to convert an array of objects into an array of arrays which then get flattened, and reduceRight allows you to invert the order in which your reducer is applied to your input values.

    Flatten

    var data = [[1,2,3], [4,5,6], [7,8,9]];
    var flatData = data.reduce( (acc, value) => {
      return acc.concat(value);
    }, []);
    
    console.log(flatData); //[1, 2, 3, 4, 5, 6, 7, 8, 9]

    Flatmap 

    var input = [
      {
        title: "Batman Begins",
        year: 2005,
        cast: [
          "Christian Bale",
          "Michael Caine",
          "Liam Neeson",
          "Katie Holmes",
          "Gary Oldman",
          "Cillian Murphy"
        ]
      },
      {
        title: "The Dark Knight",
        year: 2008,
        cast: [
          "Christian Bale",
          "Heath Ledger",
          "Aaron Eckhart",
          "Michael Caine",
          "Maggie Gyllenhal",
          "Gary Oldman",
          "Morgan Freeman"
        ]
      },
      {
        title: "The Dark Knight Rises",
        year: 2012,
        cast: [
          "Christian Bale",
          "Gary Oldman",
          "Tom Hardy",
          "Joseph Gordon-Levitt",
          "Anne Hathaway",
          "Marion Cotillard",
          "Morgan Freeman",
          "Michael Caine"
        ]
      }
    ];
    
    var flatMapInput = input.reduce((acc, value)=>{
      value.cast.forEach((star)=>{
        if(acc.indexOf(star) === -1){
          acc.push(star);
        };
      });
      
      return acc;
    }, []);
    
    
    //["Christian Bale", "Michael Caine", "Liam Neeson", "Katie Holmes", "Gary Oldman", "Cillian Murphy", "Heath Ledger", "Aaron Eckhart", "Maggie Gyllenhal", "Morgan Freeman", "Tom Hardy", "Joseph Gordon-Levitt", "Anne Hathaway", "Marion Cotillard"]

    ReduceRight

    var countDown = [1,2,3,4,"5"];
    
    var str = countDown.reduceRight((acc, value)=>{
      return acc + value;
    }, "");
    
    console.log(str); //"54321"
  • 相关阅读:
    PHPCMS快速建站系列之添加单页模版
    func_num_args(),func_get_arg(),func_get_args()
    34 个使用 Raspberry Pi 的酷创意
    解决sublime text 2总是在新窗口中打开文件
    帝国cms后台不停的登录成功
    PHP正则表达式的逆向引用与子模式 php preg_replace应用
    【采集】php str_replace
    如何设置让SFTP的用户限制在某个目录下
    win2008修改最大远程桌面连接数
    mysql查询差集
  • 原文地址:https://www.cnblogs.com/Answer1215/p/5052863.html
Copyright © 2011-2022 走看看