flat() method is used to flatten a multi-dimensional array into a single-dimensional array. This method takes an optional argument, which determines the depth of flattening. By default, it flattens the array only one level deep. For example:
const multiDimensionalArray = [1, [2, 3], [[4, 5]]]; const singleDimensionalArray = multiDimensionalArray.flat(); console.log(singleDimensionalArray);
[1, 2, 3, [4, 5]]
flatMap() method is a combination of the
flat() methods. It maps each element to a new array, then flattens the resulting arrays into a single array.
flatMap() method takes a callback function as its argument, which is called for each element in the original array. This callback function should return an array, which is then flattened. For example:
const array = [1, 2, 3, 4]; const mappedArray = array.flatMap(x => [x, x * 2]); console.log(mappedArray);
[1, 2, 2, 4, 3, 6, 4, 8]
flatMap() were added in ECMAScript 2019, and are supported in modern browsers and Node.js.