ArticleZip > Filter Out An Array With Null Values Underscore

Filter Out An Array With Null Values Underscore

Filtering out an array with null values in Underscore is a handy technique that comes in useful when dealing with JavaScript arrays that may contain unwanted null entries. Null values can clutter up your data structures and cause issues when processing data. Underscore, a popular JavaScript library, offers a straightforward method to clean up your arrays effectively.

To begin filtering out null values from an array using Underscore, you'll want to ensure you have the Underscore library included in your project. If you haven't done so already, you can easily add it to your project using npm or by including it via a script tag in your HTML file.

**Step 1: Include the Underscore Library**
If you are using npm, you can install Underscore by running the following command in your terminal or command prompt:

Bash

npm install underscore

Alternatively, you can include Underscore in your HTML file:

Html

**Step 2: Filter Out Null Values**
Now that you have the Underscore library set up, you can proceed to filter out null values from your array. Let's assume you have an array called `data` that contains both valid data and null values:

Javascript

const data = [1, null, 'hello', null, 42, null];

To filter out the null values from `data`, you can use Underscore's `_.compact()` function. This function will remove all falsy values from the array, including `null`, `undefined`, `0`, `false`, and `''` (empty string):

Javascript

const cleanedData = _.compact(data);

After applying `_.compact()`, the `cleanedData` array will contain only the non-null values from the original `data` array:

Javascript

// Output: [1, 'hello', 42]

**Step 3: Implement Custom Filtering - Filter Out Only Null Values**
If you want to filter out only null values specifically from the array while retaining other falsy values, you can create a custom filtering function using Underscore. Here's how you can achieve this:

Javascript

const customFilterNullValues = (arr) => _.filter(arr, (item) => !_.isNull(item));
const onlyNullValues = customFilterNullValues(data);

In the above example, the `customFilterNullValues` function uses Underscore's `_.filter()` function to retain only the non-null values in the array.

By following these simple steps, you can efficiently filter out null values from an array using Underscore. This method helps to clean up your data structures and ensures that you work with clean, usable data in your JavaScript applications. Try it out in your projects and experience the benefits of tidy data management!

×