Use JavaScript Array flatMap() Method to flatten up the nested array with a depth value of 1. The flatMap() method is a combination of flat() and map() methods.
arr.flatMap(callback(currentValue),thisArg)
- callback – The function to initially execute on each array element. It takes in:
- currentValue – The current element being passed from the array.
- thisArg (optional) – Value to use as
this
when executingcallback
.
This method returns a new array formed by applying a given callback function to each element of the array and then flattening the result by one level.
JavaScript Array flatMap()
A simple example code flattened the array using the flat()
method, then we have removed the negative numbers from the array using flatMap().
method.
<!DOCTYPE html>
<html>
<body>
<script type="text/javascript">
const numbers = [1, [3, 6,], [2, -3, 7, ], [-4,], 5, 8, 9];
console.log(numbers.flat(3));
const result = numbers.flatMap(number => {
return number < 0 ? [] : [number];
});
console.log(result);
</script>
</body>
</html>
Output:
Using flat() and map() Instead of flatMap()
let numbers = [1, 2, 3, 4, 5];
// incrementing each element using map()
let afterMapping = numbers.map((element) => element + 2);
// flattening the array using flat()
let afterFlattening = afterMapping.flat();
console.log(afterFlattening); // [ 3, 4, 5, 6, 7 ]
// using flatMap() instead of flat() and map()
let after_flatMap = numbers.flatMap((element) => element + 2);
console.log(after_flatMap); // [ 3, 4, 5, 6, 7 ]
Do comment if you have any doubts or suggestions on this JS array method topic.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version