Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • GfG 160: Daily DSA
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • JS Tutorial
  • JS Exercise
  • JS Interview Questions
  • JS Array
  • JS String
  • JS Object
  • JS Operator
  • JS Date
  • JS Error
  • JS Projects
  • JS Set
  • JS Map
  • JS RegExp
  • JS Math
  • JS Number
  • JS Boolean
  • JS Examples
  • JS Free JS Course
  • JS A to Z Guide
  • JS Formatter
Open In App
Next Article:
JavaScript - Use Arrays to Swap Variables
Next article icon

How to remove falsy values from an array in JavaScript ?

Last Updated : 05 Jun, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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()

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", []]

JavaScript Array.filter() Method:

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:

[]

ES6 way of Array.filter() Method:

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); 

Output
[ 1, 2, 3 ]

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', [] ]




Next Article
JavaScript - Use Arrays to Swap Variables
author
devi_johns
Improve
Article Tags :
  • JavaScript
  • Web Technologies
  • javascript-array
  • JavaScript-DSA
  • JavaScript-Methods
  • JavaScript-Questions

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. JavaScriptconst a = [10, 20, 30, 40, 50]; // Find index of value 30 const index = a.inde
    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 new
    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.Syntax
    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 ContentMethod 1: Using push() MethodMethod 2: Using concat() Met
    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 me
    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 ContentUsing the Array.slice() MethodUsing the spread OperatorUsing the Array.from() MethodUsing t
    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 s
    4 min read
    JavaScript - Create an Object From Two Arrays
    Here are the different methods to create an object from two arrays in JavaScript1. Using for-each loopThe arr.forEach() method calls the provided function once for each element of the array. JavaScriptconst a1 = ['name', 'age', 'city']; const a2 = ['Ajay', 25, 'New Delhi']; const res = {}; a1.forEac
    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 JavaScript1. 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.JavaScriptlet x = 5; let y = 10; [x, y] = [y, x];
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

'); // $('.spinner-loading-overlay').show(); let script = document.createElement('script'); script.src = 'https://assets.geeksforgeeks.org/v2/editor-prod/static/js/bundle.min.js'; script.defer = true document.head.appendChild(script); script.onload = function() { suggestionModalEditor() //to add editor in suggestion modal if(loginData && loginData.premiumConsent){ personalNoteEditor() //to load editor in personal note } } script.onerror = function() { if($('.editorError').length){ $('.editorError').remove(); } var messageDiv = $('
').text('Editor not loaded due to some issues'); $('#suggestion-section-textarea').append(messageDiv); $('.suggest-bottom-btn').hide(); $('.suggestion-section').hide(); editorLoaded = false; } }); //suggestion modal editor function suggestionModalEditor(){ // editor params const params = { data: undefined, plugins: ["BOLD", "ITALIC", "UNDERLINE", "PREBLOCK"], } // loading editor try { suggestEditorInstance = new GFGEditorWrapper("suggestion-section-textarea", params, { appNode: true }) suggestEditorInstance._createEditor("") $('.spinner-loading-overlay:eq(0)').remove(); editorLoaded = true; } catch (error) { $('.spinner-loading-overlay:eq(0)').remove(); editorLoaded = false; } } //personal note editor function personalNoteEditor(){ // editor params const params = { data: undefined, plugins: ["UNDO", "REDO", "BOLD", "ITALIC", "NUMBERED_LIST", "BULLET_LIST", "TEXTALIGNMENTDROPDOWN"], placeholderText: "Description to be......", } // loading editor try { let notesEditorInstance = new GFGEditorWrapper("pn-editor", params, { appNode: true }) notesEditorInstance._createEditor(loginData&&loginData.user_personal_note?loginData.user_personal_note:"") $('.spinner-loading-overlay:eq(0)').remove(); editorLoaded = true; } catch (error) { $('.spinner-loading-overlay:eq(0)').remove(); editorLoaded = false; } } var lockedCasesHtml = `You can suggest the changes for now and it will be under 'My Suggestions' Tab on Write.

You will be notified via email once the article is available for improvement. Thank you for your valuable feedback!`; var badgesRequiredHtml = `It seems that you do not meet the eligibility criteria to create improvements for this article, as only users who have earned specific badges are permitted to do so.

However, you can still create improvements through the Pick for Improvement section.`; jQuery('.improve-header-sec-child').on('click', function(){ jQuery('.improve-modal--overlay').hide(); $('.improve-modal--suggestion').hide(); jQuery('#suggestion-modal-alert').hide(); }); $('.suggest-change_wrapper, .locked-status--impove-modal .improve-bottom-btn').on('click',function(){ // when suggest changes option is clicked $('.ContentEditable__root').text(""); $('.suggest-bottom-btn').html("Suggest changes"); $('.thank-you-message').css("display","none"); $('.improve-modal--improvement').hide(); $('.improve-modal--suggestion').show(); $('#suggestion-section-textarea').show(); jQuery('#suggestion-modal-alert').hide(); if(suggestEditorInstance !== null){ suggestEditorInstance.setEditorValue(""); } $('.suggestion-section').css('display', 'block'); jQuery('.suggest-bottom-btn').css("display","block"); }); $('.create-improvement_wrapper').on('click',function(){ // when create improvement option clicked then improvement reason will be shown if(loginData && loginData.isLoggedIn) { $('body').append('
'); $('.spinner-loading-overlay').show(); jQuery.ajax({ url: writeApiUrl + 'create-improvement-post/?v=1', type: "POST", contentType: 'application/json; charset=utf-8', dataType: 'json', xhrFields: { withCredentials: true }, data: JSON.stringify({ gfg_id: post_id }), success:function(result) { $('.spinner-loading-overlay:eq(0)').remove(); $('.improve-modal--overlay').hide(); $('.unlocked-status--improve-modal-content').css("display","none"); $('.create-improvement-redirection-to-write').attr('href',writeUrl + 'improve-post/' + `${result.id}` + '/', '_blank'); $('.create-improvement-redirection-to-write')[0].click(); }, error:function(e) { showErrorMessage(e.responseJSON,e.status) }, }); } else { if(loginData && !loginData.isLoggedIn) { $('.improve-modal--overlay').hide(); if ($('.header-main__wrapper').find('.header-main__signup.login-modal-btn').length) { $('.header-main__wrapper').find('.header-main__signup.login-modal-btn').click(); } return; } } }); $('.left-arrow-icon_wrapper').on('click',function(){ if($('.improve-modal--suggestion').is(":visible")) $('.improve-modal--suggestion').hide(); else{ } $('.improve-modal--improvement').show(); }); const showErrorMessage = (result,statusCode) => { if(!result) return; $('.spinner-loading-overlay:eq(0)').remove(); if(statusCode == 403) { $('.improve-modal--improve-content.error-message').html(result.message); jQuery('.improve-modal--overlay').show(); jQuery('.improve-modal--improvement').show(); $('.locked-status--impove-modal').css("display","block"); $('.unlocked-status--improve-modal-content').css("display","none"); $('.improve-modal--improvement').attr("status","locked"); return; } } function suggestionCall() { var editorValue = suggestEditorInstance.getValue(); var suggest_val = $(".ContentEditable__root").find("[data-lexical-text='true']").map(function() { return $(this).text().trim(); }).get().join(' '); suggest_val = suggest_val.replace(/\s+/g, ' ').trim(); var array_String= suggest_val.split(" ") //array of words var gCaptchaToken = $("#g-recaptcha-response-suggestion-form").val(); var error_msg = false; if(suggest_val != "" && array_String.length >=4){ if(editorValue.length { jQuery('.ContentEditable__root').focus(); jQuery('#suggestion-modal-alert').hide(); }, 3000); } } document.querySelector('.suggest-bottom-btn').addEventListener('click', function(){ jQuery('body').append('
'); jQuery('.spinner-loading-overlay').show(); if(loginData && loginData.isLoggedIn) { suggestionCall(); return; } // script for grecaptcha loaded in loginmodal.html and call function to set the token setGoogleRecaptcha(); }); $('.improvement-bottom-btn.create-improvement-btn').click(function() { //create improvement button is clicked $('body').append('
'); $('.spinner-loading-overlay').show(); // send this option via create-improvement-post api jQuery.ajax({ url: writeApiUrl + 'create-improvement-post/?v=1', type: "POST", contentType: 'application/json; charset=utf-8', dataType: 'json', xhrFields: { withCredentials: true }, data: JSON.stringify({ gfg_id: post_id }), success:function(result) { $('.spinner-loading-overlay:eq(0)').remove(); $('.improve-modal--overlay').hide(); $('.create-improvement-redirection-to-write').attr('href',writeUrl + 'improve-post/' + `${result.id}` + '/', '_blank'); $('.create-improvement-redirection-to-write')[0].click(); }, error:function(e) { showErrorMessage(e.responseJSON,e.status); }, }); });
"For an ad-free experience and exclusive features, subscribe to our Premium Plan!"
Continue without supporting
`; $('body').append(adBlockerModal); $('body').addClass('body-for-ad-blocker'); const modal = document.getElementById("adBlockerModal"); modal.style.display = "block"; } function handleAdBlockerClick(type){ if(type == 'disabled'){ window.location.reload(); } else if(type == 'info'){ document.getElementById("ad-blocker-div").style.display = "none"; document.getElementById("ad-blocker-info-div").style.display = "flex"; handleAdBlockerIconClick(0); } } var lastSelected= null; //Mapping of name and video URL with the index. const adBlockerVideoMap = [ ['Ad Block Plus','https://media.geeksforgeeks.org/auth-dashboard-uploads/abp-blocker-min.mp4'], ['Ad Block','https://media.geeksforgeeks.org/auth-dashboard-uploads/Ad-block-min.mp4'], ['uBlock Origin','https://media.geeksforgeeks.org/auth-dashboard-uploads/ub-blocke-min.mp4'], ['uBlock','https://media.geeksforgeeks.org/auth-dashboard-uploads/U-blocker-min.mp4'], ] function handleAdBlockerIconClick(currSelected){ const videocontainer = document.getElementById('ad-blocker-info-div-gif'); const videosource = document.getElementById('ad-blocker-info-div-gif-src'); if(lastSelected != null){ document.getElementById("ad-blocker-info-div-icons-"+lastSelected).style.backgroundColor = "white"; document.getElementById("ad-blocker-info-div-icons-"+lastSelected).style.borderColor = "#D6D6D6"; } document.getElementById("ad-blocker-info-div-icons-"+currSelected).style.backgroundColor = "#D9D9D9"; document.getElementById("ad-blocker-info-div-icons-"+currSelected).style.borderColor = "#848484"; document.getElementById('ad-blocker-info-div-name-span').innerHTML = adBlockerVideoMap[currSelected][0] videocontainer.pause(); videosource.setAttribute('src', adBlockerVideoMap[currSelected][1]); videocontainer.load(); videocontainer.play(); lastSelected = currSelected; }

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences