[Javascript] Advanced Reduce: Flatten, Flatmap and ReduceRight

时间:2021-06-10 20:26:52

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"