Filtering Falsy Values in JavaScript Arrays

JavaScriptJavaScriptBeginner
Practice Now

This tutorial is from open-source community. Access the source code

Introduction

In this lab, we will delve into the concept of working with arrays in JavaScript. You will learn how to use the Array.prototype.filter() method to remove falsy values from an array. By the end of this lab, you will have a better understanding of how to manipulate arrays in JavaScript and be able to apply this knowledge to your own projects.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL javascript(("`JavaScript`")) -.-> javascript/BasicConceptsGroup(["`Basic Concepts`"]) javascript(("`JavaScript`")) -.-> javascript/AdvancedConceptsGroup(["`Advanced Concepts`"]) javascript/BasicConceptsGroup -.-> javascript/variables("`Variables`") javascript/BasicConceptsGroup -.-> javascript/data_types("`Data Types`") javascript/BasicConceptsGroup -.-> javascript/arith_ops("`Arithmetic Operators`") javascript/BasicConceptsGroup -.-> javascript/comp_ops("`Comparison Operators`") javascript/AdvancedConceptsGroup -.-> javascript/higher_funcs("`Higher-Order Functions`") subgraph Lab Skills javascript/variables -.-> lab-28204{{"`Filtering Falsy Values in JavaScript Arrays`"}} javascript/data_types -.-> lab-28204{{"`Filtering Falsy Values in JavaScript Arrays`"}} javascript/arith_ops -.-> lab-28204{{"`Filtering Falsy Values in JavaScript Arrays`"}} javascript/comp_ops -.-> lab-28204{{"`Filtering Falsy Values in JavaScript Arrays`"}} javascript/higher_funcs -.-> lab-28204{{"`Filtering Falsy Values in JavaScript Arrays`"}} end

How to Use Array.prototype.filter() to Create a Compact Array

To create a compact array in JavaScript, you can use the Array.prototype.filter() method to remove any falsy values from the array. Falsy values include false, null, 0, "", undefined, and NaN.

Here's an example code snippet that demonstrates how to create a compact array using Array.prototype.filter():

const compact = (arr) => arr.filter(Boolean);

You can then use the compact function to create a compact array by passing in an array as an argument. For example:

compact([0, 1, false, 2, "", 3, "a", "e" * 23, NaN, "s", 34]);
// Output: [ 1, 2, 3, 'a', 's', 34 ]

By using Array.prototype.filter() in this way, you can easily create a compact array that only contains truthy values.

Summary

Congratulations! You have completed the Compact Array lab. You can practice more labs in LabEx to improve your skills.

Other JavaScript Tutorials you may like