📜  flatmap javascript (1)

📅  最后修改于: 2023-12-03 15:15:06.023000             🧑  作者: Mango

FlatMap in JavaScript

FlatMap is a combination of two methods in JavaScript, flatMap and map. The flatMap method applies a function to each element of an array and returns a new array with the resulting flattened array.

For instance, consider the following array of arrays:

const arrays = [[1, 2], [3, 4], [5, 6]];

Using map on this array would return an array of arrays:

const mappedArray = arrays.map(arr => arr.map(val => val * 2));
// [[2, 4], [6, 8], [10, 12]]

Using flatMap instead would return a flattened array:

const flatMappedArray = arrays.flatMap(arr => arr.map(val => val * 2));
// [2, 4, 6, 8, 10, 12]

As you can see, flatMap applies the function to each element of the array and flattens the resulting array at the same time.

Syntax

The syntax for flatMap is as follows:

array.flatMap( callback(currentValue[, index[, array]])[, thisArg] )

callback: A function to apply to each element of the array.

currentValue: The current element being processed in the array.

index (optional): The index of the current element being processed in the array.

array (optional): The array flatMap was called upon.

thisArg (optional): Object to use as this when executing callback.

Examples

Here are some more examples of using flatMap:

const array1 = [1, 2, 3, 4];
const array2 = [5, 6];
const array3 = [7];

const result1 = array1.flatMap(num => [num * 2]);
// [2, 4, 6, 8]

const result2 = array1.flatMap((num, index) => [num * index]);
// [0, 2, 6, 12]

const result3 = array1.flatMap(num => [num, num + 0.5]);
// [1, 1.5, 2, 2.5, 3, 3.5, 4, 4.5]

const result4 = array1.flatMap(num => [num, num + 0.5].filter(n => n > 2));
// [2.5, 3, 3.5, 4, 4.5]

const result5 = array1.flatMap((num, index, arr) => {
  if (index === arr.length - 1) {
    return [num, array2, array3];
  } else {
    return [num];
  }
});
// [1, 2, 3, 4, [5, 6], [7]]
Conclusion

flatMap is a powerful method in JavaScript that combines the functionality of map and flat. It allows you to apply a function to each element of an array and flatten the resulting array at the same time. This can be very useful when dealing with nested arrays.