2

Remove null from an Array with Lodash

 1 year ago
source link: https://masteringjs.io/tutorials/lodash/remove-null-from-array
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Remove null from an Array with Lodash

Jun 26, 2022

To remove a null from an array, you should use lodash's filter function. It takes two arguments:

  • collection: the object or array to iterate over.
  • predicate: the function invoked per iteration.

The filter() function returns a new array containing all elements predicate returned a truthy value for. To remove null, you can call filter() with v => v !== null as the predicate.

const _ = require('lodash');

const arr = ['a', true, null, undefined, 42];

_.filter(arr, v => v !== null); // ['a', true, undefined, 42]

To remove null using filter, you can use the _.isNull function as the predicate. Simply add a negate in front of the isNull and all null values will be filtered out.

const _ = require('lodash');

const array = ['a', true, null, undefined, 42]; // ['a', true, undefined, 42]

_.filter(array, el => !_.isNull(el));

More Lodash Tutorials


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK