0 day streak
javascript / intermediate
Snippet

Efficient Transformation with Array.flatMap()

flatMap() combines map() and flat() into one operation. It applies a function to each element and then flattens the result by one level, which is more performant than chain calling both methods.

snippet.js
javascript
1
2
3
4
const tags = ['js,ts', 'node', 'web,css'];
const list = tags.flatMap(tag => tag.split(','));
console.log(list); // ['js', 'ts', 'node', 'web', 'css']
Breakdown
1
tags.flatMap(tag => tag.split(','))
Splits strings into arrays and immediately flattens them into a single list.