How to use Array.prototype.flatMap() In Javascript
Using Array.prototype.flatMap(), you can remove falsy values by mapping each element to an array containing the element if it’s truthy, or an empty array if it’s falsy. The resulting arrays are then flattened into a single array of truthy values.
Example: In this example The filteredArray filters out falsy values from the array using flatMap(), resulting in a new array containing only truthy values.
const array = [0, 1, false, 2, '', 3, null, undefined, NaN];
const filteredArray = array.flatMap(value => value ? [value] : []);
console.log(filteredArray);
Output
[ 1, 2, 3 ]
How to remove falsy values from an array in JavaScript ?
Falsy/Falsey Values: In JavaScript, there are 7 falsy values, which are given below
- false
- zero(0,-0)
- empty string(“”, ‘ ‘ , ` `)
- BigIntZero(0n,0x0n)
- null
- undefined
- NaN
In JavaScript, the array accepts all types of falsy values. Let’s see some approaches on how we can remove falsy values from an array in JavaScript:
- Using for-each loop
- Using the Array.filter method
- Using Array.reduce method
- Using for…of loop
Example:
Input: [23, 0, “gfg”, false, true, NaN, 12, “hi”, undefined, [], “”]
Output: [23, “gfg”, true, 12, “hi”, []]
Input: [“”, 0, false, undefined, NaN, null]
Output: []
Approach: There are many approaches to achieve this some of them are the following:
Table of Content
- JavaScript for..each loop:
- JavaScript Array.filter() Method
- ES6 way of Array.filter() Method
- JavaScript Array.reduce() Method
- JavaScript for…of loop
- JavaScript for loop
- Using Array.prototype.flatMap()