惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Spread Privacy
Spread Privacy
K
Kaspersky official blog
Application and Cybersecurity Blog
Application and Cybersecurity Blog
Forbes - Security
Forbes - Security
Hacker News - Newest:
Hacker News - Newest: "LLM"
The Last Watchdog
The Last Watchdog
SecWiki News
SecWiki News
Attack and Defense Labs
Attack and Defense Labs
Google DeepMind News
Google DeepMind News
Security Archives - TechRepublic
Security Archives - TechRepublic
S
Secure Thoughts
WordPress大学
WordPress大学
Microsoft Security Blog
Microsoft Security Blog
P
Proofpoint News Feed
云风的 BLOG
云风的 BLOG
V
Visual Studio Blog
Security Latest
Security Latest
TaoSecurity Blog
TaoSecurity Blog
Cyberwarzone
Cyberwarzone
S
SegmentFault 最新的问题
Cloudbric
Cloudbric
aimingoo的专栏
aimingoo的专栏
S
Schneier on Security
N
Netflix TechBlog - Medium
MyScale Blog
MyScale Blog
T
The Blog of Author Tim Ferriss
H
Hacker News: Front Page
C
Cybersecurity and Infrastructure Security Agency CISA
小众软件
小众软件
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
AWS News Blog
AWS News Blog
AI
AI
G
GRAHAM CLULEY
IT之家
IT之家
P
Privacy & Cybersecurity Law Blog
L
Lohrmann on Cybersecurity
Last Week in AI
Last Week in AI
D
Docker
Recent Announcements
Recent Announcements
O
OpenAI News
T
Threat Research - Cisco Blogs
GbyAI
GbyAI
S
Security @ Cisco Blogs
T
Troy Hunt's Blog
C
Check Point Blog
博客园 - 三生石上(FineUI控件)
A
About on SuperTechFans
The Cloudflare Blog
阮一峰的网络日志
阮一峰的网络日志
N
News and Events Feed by Topic

Dmitri Pavlutin Blog

Pure Functions in JavaScript: A Beginner's Guide Record Type in TypeScript: A Quick Intro How to Write Comments in React: The Good, the Bad and the Ugly 4 Ways to Create an Enum in JavaScript React forwardRef(): How to Pass Refs to Child Components TypeScript Function Types: A Beginner's Guide How to Use v-model to Access Input Values in Vue Mastering Vue refs: From Zero to Hero Environment Variables in JavaScript: process.env 5 Must-Know Differences Between ref() and reactive() in Vue How to Destructure Props in Vue (Composition API) Triangulation in Test-Driven Development How to Use nextTick() in Vue Programming to Interface Vs to Implementation Array Grouping in JavaScript: Object.groupBy() How to Access ES Module Metadata using import.meta JSON Modules in JavaScript How to Trim Strings in JavaScript TypeScript Function Overloading How to Debounce and Throttle Callbacks in Vue How to Show/Hide Elements in Vue Sparse vs Dense Arrays in JavaScript How to Fill an Array with Initial Values in JavaScript Covariance and Contravariance in TypeScript What are Higher-Order Functions in JavaScript? How to Use TypeScript with React Components Index Signatures in TypeScript How to Use React useReducer() Hook unknown vs any in TypeScript A Guide to React Context and useContext() Hook How to Use Promise.any() 2 Ways to Remove a Property from an Object in JavaScript 'return await promise' vs 'return promise' in JavaScript How to Use Promise.allSettled() How to Use fetch() with JSON JavaScript Promises: then(f,f) vs then(f).catch(f) What is a Promise in JavaScript? How to Use Promise.all() A Simple Guide to Component Props in React Don't Stop Me Now: How to Use React useTransition() hook A Simple Explanation of JavaScript Variables: const, let, var ES Modules Dynamic Import How to Memoize with React.useMemo() How to Cleanup Async Effects in React Why Math.max() Without Arguments Returns -Infinity How to Debounce and Throttle Callbacks in React Don't Confuse Function Expressions and Function Declarations in JavaScript How to Use ES Modules in Node.js Solving a Mystery Behavior of parseInt() in JavaScript How to Use Array Reduce Method in JavaScript 3 Ways to Merge Arrays in JavaScript A Guide to Jotai: the Minimalist React State Management Library The Difference Between Values and References in JavaScript How to Implement a Queue in JavaScript A Helpful Algorithm to Determine "this" value in JavaScript React useRef() Hook Explained in 3 Steps 7 Interview Questions on "this" keyword in JavaScript. Can You Answer Them? How to Greatly Enhance fetch() with the Decorator Pattern 7 Interview Questions on JavaScript Closures. Can You Answer Them? What's a Method in JavaScript? array.sort() Does Not Simply Sort Numbers in JavaScript How to Solve the Infinite Loop of React.useEffect() The New Array Method You'll Enjoy: array.at(index) What's the Difference between DOM Node and Element? Why Promises Are Faster Than setTimeout()? Everything About Callback Functions in JavaScript How React Updates State 5 Mistakes to Avoid When Using React Hooks 5 Best Practices to Write Quality JavaScript Variables Type checking in JavaScript: typeof and instanceof operators 3 Ways to Check if a Variable is Defined in JavaScript React Forms Tutorial: Access Input Values, Validate, Submit Forms Prototypal Inheritance in JavaScript How to Timeout a fetch() Request How to Learn JavaScript If You're a Beginner A Simple Explanation of React.useEffect() A Simple Explanation of JavaScript Iterators How to Use React Controlled Inputs Everything about null in JavaScript How to Use Fetch with async/await Getting Started with Arrow Functions in JavaScript An Interesting Explanation of async/await in JavaScript Front-end Architecture: Stable and Volatile Dependencies Is it Safe to Compare JavaScript Strings? How to Access Object's Keys, Values, and Entries in JavaScript What Actually is a String in JavaScript? 3 Ways to Shallow Clone Objects in JavaScript (w/ bonuses) Checking if an Array Contains a Value in JavaScript JavaScript Event Delegation: A Beginner's Guide How to Parse URL in JavaScript: hostname, pathname, query, hash 3 Ways to Detect an Array in JavaScript How to Get the Screen, Window, and Web Page Sizes in JavaScript 3 Ways to Check If an Object Has a Property/Key in JavaScript How to Compare Objects in JavaScript Object.is() vs Strict Equality Operator in JavaScript Own and Inherited Properties in JavaScript 5 Differences Between Arrow and Regular Functions How to Use Object Destructuring in JavaScript Your Guide to React.useCallback() 5 JavaScript Scope Gotchas
A Smarter JavaScript Mapper: array.flatMap()
Dmitri Pavlutin · 2021-12-31 · via Dmitri Pavlutin Blog

array.map() is a very useful mapper function: it takes an array and a mapper function, then returns a new mapped array.

However, there's an alternative to array.map(): the array.flatMap() (available starting ES2019). This method gives you the ability to map, but also to remove or even add new items in the resulting mapped array.

1. Smarter mapper

Having an array of numbers, how would you create a new array with the items doubled?

Using the array.map() function is a good approach:


const numbers = [0, 3, 6];

const doubled = numbers.map(n => n * 2);

console.log(doubled); // logs [0, 6, 12]


Open the demo.

numbers.map(number => 2 * number) maps numbers array to a new array where each number is doubled.

For the cases when you need to map one to one, meaning that the mapped array will have the same number of items as the original array, array.map() works pretty well.

But what if you need to double the numbers of an array and also skip zeroes from the mapping?

Using array.map() directly isn't possible, because the method always creates a mapped array with the same number of items as the original array. But you can use a combination of array.map() and array.filter():


const numbers = [0, 3, 6];

const doubled = numbers

.filter(n => n !== 0)

.map(n => n * 2);

console.log(doubled); // logs [6, 12]


Open the demo.

doubled array now contains items of numbers multiplied by 2 and also doesn't contain any zeroes.

Ok, a combination of array.map() and array.filter() maps and filters arrays. But is there a shorter approach?

Yes! Thanks to array.flatMap() method you can perform mapping and removing items with just one method call.

Here's how you can use array.flatMap() to return a new mapped array with items doubled, at the same time filtering zeroes 0:


const numbers = [0, 3, 6];

const doubled = numbers.flatMap(number => {

return number === 0 ? [] : [2 * number];

});

console.log(doubled); // logs [6, 12]


Open the demo.

By using only the numbers.flatMap() you can map an array to another array, but also skip certain elements from mapping.

Let's see in more detail how array.flatMap() works.

2. array.flatMap()

array.flatMap() function accepts a callback function as an argument and returns a new mapped array:


const mappedArray = array.flatMap((item, index, origArray) => {

// ...

return [value1, value2, ..., valueN];

}[, thisArg]);


The callback function is invoked upon each iteam in the original array with 3 arguments: the current item, index, and the original array. The array returned by the callback is then flattened by 1 level deep, and the resulting items are added to the mapped array.

Also, the method accepts a second, optional, argument indicating the this value inside of the callback.

The simplest way you can use array.flatMap() is to flatten an array that contains items as arrays:


const arrays = [[2, 4], [6]];

const flatten = arrays.flatMap(item => item);

console.log(flatten); // logs [2, 4, 6]


Open the demo.

In the example above arrays contains arrays of numbers: [[2, 4], [6]]. Calling arrays.flatMap(item => item) flattens the array to [2, 4, 6].

But array.flatMap() can do more beyond simple flattening. By controlling the number of array items you return from the callback, you can:

  • remove the item from the resulting array by returning an empty array []
  • modify the mapped item by returning an array with one new value [newValue]
  • or add new items by returning an array with multiple values: [newValue1, newValue2, ...].

For example, as you saw in the previous section, you can create a new array by doubling the items, but also remove the zeroes 0:


const numbers = [0, 3, 6];

const doubled = numbers.flatMap(number => {

return number === 0 ? [] : [2 * number];

});

console.log(doubled); // logs [6, 12]


Open the demo.

Let's look into more detail on how the example above works.

The callback function returns an empty array [] if the current item is 0. It means that when being flattened, the empty array [] provides no value at all.

If the current iterated item is non-zero, then [2 * number] is returned. When [2 * number] array is flattened, only 2 * number is added into the resulting array.

You can also use array.flatMap() to increase the number of items in the mapped array.

For example, the following code snipped maps an array of numbers to a new array by adding doubled and tripled numbers:


const numbers = [1, 4];

const trippled = numbers.flatMap(number => {

return [number, 2 * number, 3 * number];

});

console.log(trippled);

// logs [1, 2, 3, 4, 8, 12]


Open the demo.

3. Conclusion

array.flatMap() method is the way to go if you want to map an array to a new array, but also have control over how many items you'd like to add to the new mapped array.

The callback function of array.flatMap(callback) is called with 3 arguments: the current iterated item, index, and the original array. The array returned from the callback function is then flattened at 1 level deep, and the resulting items are inserted in the resulting mapped array.

Note that if you just want to map a single item to a single new value, then strive to the standard array.map().

Challenge: can you implement a function filter(array, predicateFunc) that would return a new filtered array using predicateFunc? Please use array.flatMap() for your implementation.