avaScript 中的 flatMap()
方法是数组处理的一把利器,它巧妙地结合了 map()
和 flat()
的功能,让代码更简洁、更优雅。
什么是 flatMap()?
const newArray = array.flatMap(callback(currentValue, index, array) {
// 返回处理后的元素
}, thisArg);
callback
:对每个元素执行的函数
thisArg
:(可选)执行 callback 时用作 this 的值
使用场景与示例
1. 扁平化嵌套数组结构
// 传统方法
const result1 = [1, 2, 3].map(x => [x * 2]).flat();
// 使用 flatMap
const result2 = [1, 2, 3].flatMap(x => [x * 2]);
// 两者结果相同:[2, 4, 6]
2. 过滤并转换元素
flatMap()
可以同时完成筛选和转换的工作:
const words = ["Hello world"","JavaScript is awesome"];
const allWords = words.flatMap(phrase => phrase.split(""));
//结果:["Hello","world""JavaScript","is""awesome"]
3. 处理可能存在的元素
const userInput = ["apple","","banana", null, "orange"];
const validInputs = userInput.flatMap(item =>{
return item ? [item] : []
})
// 结果: ["apple,","banana","orange"]
4. 展开对象数组中的一对多关系
const orders =[
{ id:1,items:["book","pen"] },
{id:2,items:["'notebook"]}
{ id:3,items: ["eraser"","ruler"","pencil"]}
1;
const allItems = orders.flatMap(order => order.items);
// 结果:["book","pen", "notebook", "eraser","pencil"]
性能优势
使用 flatMap()
相比分别调用 map()
和 flat()
有性能优势:
- 只需遍历数组一次
- 减少中间数组的创建
- 代码更加简洁
注意事项
flatMap()
只会将结果扁平化一层
- 如果需要多层扁平化,仍需使用
flat(depth)
- IE 浏览器不支持此方法,需要使用 polyfill
实际应用案例
文本分析
const texts =["JavaScript is amazing","flatMap is useful"];
const wordCounts = texts.flatMap(text => {
const words = text.split("");
return words.map(word =>(f word, length: word.length }));
})
// 结果是所有单词及其长度的对象数组
数据处理管道
const userData = [
{ name: "Alice", scores: [85, 90, 92] },
{ name: "Bob", scores: [75, 80] },
{ name: "Charlie", scores: [95, 85, 90, 100] }
];
const highScores = userData
.flatMap(user =>
user.scores.map(score => ({ name: user.name, score }))
)
.filter(item => item.score >= 90);
// 结果是所有90分以上成绩的对象数组