
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] : []
📖 Read Next
- • How to create a simple CRUD application using only JavaScript
- • What is map() function in JavaScript? Benefits of using map() function in your application.
- • Generate Clean HTML Tables Instantly
- • How to get the x Character (any particular character) in a String using charAt() method in JavaScript
