Trusted answers to developer questions

How to quickly filter out all falsy values from an array in JS

Get the Learn to Code Starter Pack

Break into tech with the logic & computer science skills you’d learn in a bootcamp or university — at a fraction of the cost. Educative's hand-on curriculum is perfect for new learners hoping to launch a career.

We use the filter method to remove falsy values from an array. The filter method filters out all the values that return false when passed to a function. When you use filter and pass a Boolean constructor, you can quickly filter out all the falsy values from the array.

Syntax

array.filter(function(currentValue, index, array), thisValue)

Parameters

Parameter

Description

function(currentValue, index, array)

(Required)

A function or search criteria to be used to filter values in the array.


The function accepts three arguments:

  1. CurrentValue (Required) - The current element that needs to be filtered.
  2. Index (Optional) - The index of the current element being processed in the array.
  3. Array (Optional) - The array object being called upon.

thisValue

(Optional)

thisValue is passed in case the parameter is empty.

Return value

filter returns a new array with the elements that pass the test. If no elements pass the test, an empty array will be returned.

Note: There are only six falsy values in JavaScript: undefined , null , NaN , 0 , "", and false.

Code

const arr = [1, "test", undefined, null, 5, false, "", 3, NaN];
const result = arr.filter(Boolean); // = > [1, "test", 5, 3]
console.log(result);

Explanation

  • Javascript has first-class functions. This is why you can directly pass the Boolean constructor function to filter.
  • arr.filter(Boolean) filters all the falsy values present in the array and returns a new array.

RELATED TAGS

javascript
boolean

CONTRIBUTOR

Non Stop Learning...
Copyright ©2024 Educative, Inc. All rights reserved
Did you find this helpful?