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"
  • 相关阅读:
    ASP设计常见问题及解答精要
    网页脚本加密解密
    有关表格边框的css样式表语法说明
    彻底搞定 Grub
    三千年来振奋过中国人的29句口号(是中国人就看看!)
    在Unix/Linux上令(java)JVM支持中文输出
    windows xp 下eclipse3.0.2+eclipseme+j2me wireless tooltik开发环境的配置
    在网页上显示公式
    Oracle认证考试详细介绍
    算法和数据结构排序快速排序
  • 原文地址:https://www.cnblogs.com/Answer1215/p/5052863.html
Copyright © 2011-2022 走看看