码迷,mamicode.com
首页 > 编程语言 > 详细

[Javascript] Advanced Reduce: Flatten, Flatmap and ReduceRight

时间:2015-12-17 06:54:29      阅读:297      评论:0      收藏:0      [点我收藏+]

标签:

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"

 

[Javascript] Advanced Reduce: Flatten, Flatmap and ReduceRight

标签:

原文地址:http://www.cnblogs.com/Answer1215/p/5052863.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!