[JavaScript] array method - flatMap()

In JavaScript, flatMap()is one of the array methods, which combines the functionality of the map()and flat()methods. It first performs a map operation on each element in the array, and then "flattens" the map result array into a new array. In other words, flatMap()nested array structures can be processed and expanded together.

The basic syntax is as follows:

const newArray = array.flatMap(function(element, index, array) {
    
    
  // 在这里编写映射操作,返回一个数组
});
  • element: The currently traversed array element.
  • index: The index of the current element.
  • array: the original array.

Example:

const words = ['hello', 'world', 'from', 'openai'];

// 对每个单词进行分割,并将结果展开到一个新数组
const letters = words.flatMap(word => word.split(''));

console.log(letters); // ['h', 'e', 'l', 'l', 'o', 'w', 'o', 'r', 'l', 'd', 'f', 'r', 'o', 'm', 'o', 'p', 'e', 'n', 'a', 'i']

In this example, flatMap()the method first performs split('')the operation on each word, splitting the words into character arrays, and then unrolls all of these character arrays into a new flattened array.

Note that, unlike with map(), flatMap()empty items in the returned array are automatically removed, so no extra steps are required to handle empty items.

flatMap()Very useful when dealing with nested array structures to simplify code and reduce intermediate steps.

Guess you like

Origin blog.csdn.net/XiugongHao/article/details/132348036