Filtering Falsy Values in JavaScript Arrays

Beginner

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.

This is a Guided Lab, which provides step-by-step instructions to help you learn and practice. Follow the instructions carefully to complete each step and gain hands-on experience. Historical data shows that this is a beginner level lab with a 100% completion rate. It has received a 100% positive review rate from learners.

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.