Learn to Flatten and Flatmap Arrays with Reduce

Share this video with your friends

Send Tweet

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.

Claudio Guerra
Claudio Guerra
~ 3 years ago

With this you could flatten virtually infinitely nested arrays :)

function flatten(data){return data.reduce(function(acc, value){return acc.concat(value.constructor === Array ? flatten(value) : value)}, [])}

Pavlo Iuriichuk
Pavlo Iuriichuk
~ 3 years ago

how about using a filter instead of forEach inside the reducer?

Karl Hadwen
Karl Hadwen
~ 2 years ago

Wouldn't it make more sense to use:

const cast = movies.reduce((acc, cur) => [...new Set(cur.cast)]);