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"
  • 相关阅读:
    DMR 系统平方根升余弦滚降滤波器设计SRRC及仿真图
    相似项
    第三种主题暗黑系
    汽油性能
    放平心态
    Python 中的哈希表
    第二种主题
    win7旗舰版 一键激活
    java与c++的不同感受
    c代码待用c++代码
  • 原文地址:https://www.cnblogs.com/Answer1215/p/5052863.html
Copyright © 2011-2022 走看看