Find Even numbers in Array using flatMap() in JavaScript

← PrevNext →

There are few simple methods in JavaScript to filter even or odd numbers in an Array. Like you can loop through each number in the array and check whether the number odd or even or in the array and check whether the number odd or even or you can use the built-in filter() method to do the same. However, there’s another interesting built-in method in JavaScript called flatMap() that you can use to quickly filter or find even (or odd) numbers in an array.

Get even numbers from array using flatMap() in JavaScript

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>
Try it

// Use this code to get odd numbers.

x => x % 2 === 1 ? [x] : []

Related articles

How to create a simple CRUD application using only JavaScript
What is map() function in JavaScript? Benefits of using map() function in your application.
How to get the x Character (any particular character) in a String using charAt() method in JavaScript

← PreviousNext →