What is flatMap() method in JavaScript? I have already explained about it in detail in my previous article. Go through it please.
Now, let’s see how we can extract or filter out only even numbers from an array.
The Script
<script> const getEvenNumbers = () => { let arr_numbers = [4,5,7,8,14,45,76]; let arr_flattened = arr_numbers.flatMap( x => x % 2 === 0 ? [x] : [] // filter and return only "even" numbers. ) console.log(arr_flattened); // Output: 4,8,14,76 } getEvenNumbers(); </script>
// Use this code to get odd numbers.
x => x % 2 === 1 ? [x] : []