How to remove falsy values from an array in JavaScript ?
Last Updated :
05 Jun, 2024
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:
JavaScript for..each loop:
In this approach, we will iterate the array using the for..each loop and at every iteration, we check if the value is truthy, if it is truthy then we push the value in a newly created array, and then we return the new array.
Example: In this example, we will be using Javascript forEach() loop to remove the falsy values.
JavaScript
let arr = [23, 0, "gfg", false, true, NaN, 12, "hi", undefined, [], ""];
function removeFalsey(arr) {
// newly created array
let newArr = [];
// Iterate the array using the forEach loop
arr.forEach((k) => {
// check for the truthy value
if (k) {
newArr.push(k);
}
});
// return the new array
return newArr;
}
console.log(removeFalsey(arr));
Output:
[23, "gfg", true, 12, "hi", []]
In this approach, we are using the array.filter method. The filter method checks the array and filters out the false values of the array and returns a new array.
Example: In this example, we will be using the Array.filter() method to remove the false values from the array.
JavaScript
let arr = ["", 0, false, undefined, NaN, null];
function removeFalsey(arr) {
// Applying the filter method on the array
return arr.filter((k) => {
// Checking if the value is truthy
if (k) {
return k;
}
});
}
console.log(removeFalsey(arr));
Output:
[]
If you can use this es6 sentence.
Example: In this example, we will use the Javascript Array.filter() method in ES6.
JavaScript
let arr = [23, 0, "gfg", false, true, NaN, 12, "hi", undefined, [], ""];
function removeFalsey(arr) {
// Return the first parameter of the callback function
return arr.filter((val) => val);
}
console.log(removeFalsey(arr));
Output:
[23, "gfg", true, 12, "hi", []]
Passing Boolean Value: You can also achieve this by passing the Boolean constructor as the argument of the filter method.
Example: In this example, we will a boolean constructor in the argument of the filter method.
JavaScript
let arr = [23, 0, "gfg", false, true, NaN, 12, "hi", undefined, [], ""];
function removeFalsey(arr) {
// Passing Boolean constructor inside filter
return arr.filter(Boolean);
}
console.log(removeFalsey(arr));
Output:
[23, "gfg", true, 12, "hi", []]
JavaScript Array.reduce() Method:
Using the Array.reduce method we iterate the array and initialize the accumulator with an empty array and if the current value is not a falsy value then we return a concatenated value of the accumulator else we return the accumulator only.
Example: In this example, we will use the Javascript Array.reduce() method to remove the falsy values from the array.
JavaScript
let arr = [23, 0, "gfg", false, true, NaN, 12, "hi", undefined, [], ""];
function removeFalsey(arr) {
return arr.reduce((acc, curr) => {
// Check if the truthy then return concatenated value acc with curr.
// else return only acc.
if (curr) {
return [...acc, curr];
} else {
return acc;
}
}, []); // Initialize with an empty array
}
console.log(removeFalsey(arr));
Output:
[23, "gfg", true, 12, "hi", []]
JavaScript for…of loop:
Using for…of loop iterate the array and check every item if it is falsy or truthy. If the item is truthy then push the item to a newly created array.
Example: In this example, we will use Javascript for..of loop to remove the falsy values from the array.
JavaScript
let arr = [23, 0, "gfg", false, true, NaN, 12, "hi", undefined, [], ""];
function removeFalsey(arr) {
// Create a new array
let output = [];
for (x of arr) {
if (x) {
// Check if x is truthy
output.push(x);
}
}
return output;
}
console.log(removeFalsey(arr));
Output:
[23, "gfg", true, 12, "hi", []]
JavaScript for loop:
Using for loop iterate the array and check every item if it is falsy or truthy. If the item is truthy then push the item to a newly created array.
Example: In this example, we will use the Javascript for loop to remove the falsy values from the array.
JavaScript
let arr = [23, 0, "gfg", false, true, NaN, 12, "hi", undefined, [], ""];
function removeFalsey(arr) {
// Create a new array
let output = [];
for (let i = 0; i < arr.length; i++) {
if (arr[i]) {
output.push(arr[i]);
}
}
return output;
}
console.log(removeFalsey(arr));
Output:
[23, "gfg", true, 12, "hi", []]
Using Array.prototype.flatMap()
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.
JavaScript
const array = [0, 1, false, 2, '', 3, null, undefined, NaN];
const filteredArray = array.flatMap(value => value ? [value] : []);
console.log(filteredArray);
JavaScript Array.prototype.reduceRight() Method:
Using the Array.prototype.reduceRight() method, we iterate over the array from the last element to the first element. Similar to the reduce() approach, we initialize the accumulator with an empty array and add elements to it only if they are truthy.
Example: In this example, we use the reduceRight() method to remove falsy values from an array.
JavaScript
let arr = [23, 0, "gfg", false, true, NaN, 12, "hi", undefined, [], ""];
function removeFalsey(arr) {
return arr.reduceRight((acc, curr) => {
// Check if the current value is truthy, then concatenate it to the accumulator
if (curr) {
return [curr, ...acc];
} else {
return acc;
}
}, []); // Initialize with an empty array
}
console.log(removeFalsey(arr));
Output[ 23, 'gfg', true, 12, 'hi', [] ]
Similar Reads
JavaScript - Find Index of a Value in Array
Here are some effective methods to find the array index with a value in JavaScript. Using indexOf() - Most Used indexOf() returns the first index of a specified value in an array, or -1 if the value is not found. [GFGTABS] JavaScript const a = [10, 20, 30, 40, 50]; // Find index of value 30 const in
2 min read
JavaScript - How to Get First N Elements from an Array?
There are different ways to get the first N elements from array in JavaScript. Examples: Input:arr = [1, 2, 3, 4, 5, 6], n = 3 Output: [1, 2, 3] Input:arr = [6, 1, 4, 9, 3, 5, 7], n = 4Output: [6, 1, 4, 9]1. Using slice() MethodThe slice() method is used to extract a part of an array and returns a n
4 min read
How to Copy Array by Value in JavaScript ?
There are various methods to copy array by value in JavaScript. 1. Using Spread OperatorThe JavaScript spread operator is a concise and easy metho to copy an array by value. The spread operator allows you to expand an array into individual elements, which can then be used to create a new array. Synt
4 min read
What is the most efficient way to concatenate N arrays in JavaScript ?
In this article, we will see how to concatenate N arrays in JavaScript. The efficient way to concatenate N arrays can depend on the number of arrays and the size of arrays. To concatenate N arrays, we use the following methods: Table of Content Method 1: Using push() MethodMethod 2: Using concat() M
3 min read
How to Merge Two Arrays and Remove Duplicate Items in JavaScript?
Given two arrays, the task is to merge both arrays and remove duplicate items from merged array in JavaScript. The basic method to merge two arrays without duplicate items is using spread operator and the set constructor. 1. Using Spread Operator and Set() ConstructorThe Spread Operator is used to m
3 min read
How to clone an array in JavaScript ?
In JavaScript, cloning an array means creating a new array with the same elements as the original array without modifying the original array. Here are some common use cases for cloning an array: Table of Content Using the Array.slice() MethodUsing the spread OperatorUsing the Array.from() MethodUsin
6 min read
JavaScript - Check if JS Array Includes a Value?
To check if an array includes a value we can use JavaScript Array.includes() method. This method returns a boolean value, if the element exists it returns true else it returns false. 1. Using Array.includes() Method - Mostly Used The JS array.includes() method returns true if the array contains the
4 min read
JavaScript - Create an Object From Two Arrays
Here are the different methods to create an object from two arrays in JavaScript 1. Using for-each loopThe arr.forEach() method calls the provided function once for each element of the array. [GFGTABS] JavaScript //Driver Code Starts{ const a1 = ['name', 'age', 'city']; const
3 min read
How to remove falsy values from an array in JavaScript ?
Falsy/Falsey Values: In JavaScript, there are 7 falsy values, which are given below falsezero(0,-0)empty string("", ' ' , ` `)BigIntZero(0n,0x0n)nullundefinedNaNIn 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 Ja
6 min read
JavaScript - Use Arrays to Swap Variables
Here are the different methods to swap variables using arrays in JavaScript 1. Using Array DestructuringArray destructuring is the most efficient and modern way to swap variables in JavaScript. This method eliminates the need for a temporary variable. [GFGTABS] JavaScript let x = 5; let y = 10; [x,
3 min read