I have been taking some courses on Udemy to improve my JavaScript / ES6 skills and I would like to hear from experienced front end developers some examples on how they used the methods map()
, filter()
, reduce()
and find()
when building real applications.
If you could contribute with some of your cases I would use them to exercise what I have learned and gain practice with more complex scenarios than the examples I have on my courses.
Thank you very much
Here is a (paraphrased) thing I wrote a work a couple weeks ago that contains filters, maps, and a reduce. (Some of them are observable pipes, but those work the same way.)
this.selectOptions$ = this.observablesMap.get('workThing$', undefined, this.system).pipe(
.filter((feed) => feed && !isEmpty(feed)),
.map((feed) => feed.Stuff
.filter((thing) => this.featuresService.getOptions('WorkThingStuff'.types.indexOf(thing.systemType) >= 0)
.reduce((grouped, things) => {
for (let group of groups) {
if (group.title === thing.systemType) {
group.options.push(thing.value);
return grouped;
}
}
grouped.push({title: thing.systemType, options: [thing.value]});
return grouped;
}, [])))
);
Here are some cases how I use them.
Map: when I iterate over an array and output the contents wrapped around with JSX elements. Also returning new states in my reducer functions in Redux.
Filter: Literally when I filter by different categories, or match items when user clicks on buttons to be shown different items.
Reduce: Adding up items in an array to get their sum.
Find: To find a specific item and get more info by provided (usually) id.