ECMAScript question detail
Array flat and flatMap
Prior to ES2019, you need to use reduce() or concat() methods to get a flat array.
function flatten(arr) {
const flat = [].concat(...arr);
return flat.some(Array.isArray) ? flatten(flat) : flat;
}
flatten([ [1, 2, 3], ['one', 'two', 'three', [22, 33] ], ['a', 'b', 'c'] ]);
In ES2019, the flat() method is introduced to 'flattens' the nested arrays into the top-level array. The functionality of this method is similar to Lodash's _.flattenDepth() function. This method accepts an optional argument that specifies the number of levels a nested array should be flattened and the default nested level is 1.
Note: If there are any empty slots in the array, they will be discarded.
const numberArray = [[1, 2], [[3], 4], [5, 6]];
const charArray = ['a', , 'b', , , ['c', 'd'], 'e'];
const flattenedArrOneLevel = numberArray.flat(1);
const flattenedArrTwoLevel = numberArray.flat(2);
const flattenedCharArrOneLevel = charArray.flat(1);
console.log(flattenedArrOneLevel); // [1, 2, [3], 4, 5, 6]
console.log(flattenedArrTwoLevel); // [1, 2, 3, 4, 5, 6]
console.log(flattenedCharArrOneLevel); // ['a', 'b', 'c', 'd', 'e']
Whereas, flatMap() method combines map() and flat() into one method. It first creates a new array with the return value of a given function and then concatenates all sub-array elements of the array.
const numberArray1 = [[1], [2], [3], [4], [5]];
console.log(numberArray1.flatMap(value => [value * 10])); // [10, 20, 30, 40, 50]