假设我们有一个包含一些学生的数组,每个学生有多个成绩,我们想要得到所有成绩的一个扁平化数组。
const students = [ { name: 'Alice', scores: [90, 95, 85], }, { name: 'Bob', scores: [80, 85, 88], }, { name: 'Charlie', scores: [70, 75, 78], }, ]; // 使用 flatMap 将所有学生的成绩展平为一个数组 const allScores = students.flatMap(student => student.scores); console.log(allScores); // [90, 95, 85, 80, 85, 88, 70, 75, 78]
解释
-
原始数组
students
:const students = [ { name: 'Alice', scores: [90, 95, 85], }, { name: 'Bob', scores: [80, 85, 88], }, { name: 'Charlie', scores: [70, 75, 78], }, ];
这个数组包含了三个学生,每个学生都有一个
scores
属性,其中包含该学生的成绩数组。 -
映射和扁平化操作
flatMap
:const allScores = students.flatMap(student => student.scores);
flatMap
对每个学生对象调用一次函数student => student.scores
,该函数返回学生的成绩数组。flatMap
会将这些返回的数组展平成一个单一的数组。
-
结果
allScores
:console.log(allScores); // [90, 95, 85, 80, 85, 88, 70, 75, 78]
结果是一个包含所有学生成绩的扁平化数组。
通过 flatMap
,我们可以在一次操作中完成数组的映射和展平,从而简化代码。在这个例子中,flatMap
首先将每个学生的成绩数组提取出来,然后将所有成绩数组展平成一个单一数组。