DEV Community

Discussion on: 🧙‍♂️ 9 JavaScript Tips & Tricks To Code Like A Wizard

Collapse
 
tiagojpdias profile image
Tiago Dias

One that I often:

const collection = [obj1, obj2, undefined, obj3, undefined];
const cleanCollection = collection.filter(Boolean);
// [obj1, obj2, obj3]
Enter fullscreen mode Exit fullscreen mode

At first it may look odd but we just avoid one extra anonymous function and provide the .filter() argument into the Boolean() function directly. Short and clean.

Boolean() will return true for truthy values and false for falsy values (null, undefined, 0, '', false).

It's a nice way to clean up arrays. Use it wisely.

PS: [] and {} are not falsy values as you may think at first...

const collection = [obj1, obj2, {}, obj3, undefined];
const cleanCollection = collection.filter(Boolean);
// [obj1, obj2, {}, obj3]
Enter fullscreen mode Exit fullscreen mode
Collapse
 
orkhanjafarovr profile image
Orkhan Jafarov • Edited

Yep! That's nice one to work with array of primitives.
I had this small helper that export from helper file.

export const clearArray = value => {
  const types = {
    string: v => !!v,
    object: v => v && (
        Array.isArray(v) ? v : Object.keys(v)
    ).length,
    number: v => !Number.isNaN(v),
  }
  return types?.[typeof value]?.(value) ?? value;
};

and then import it and I put it as argument in the filter method.

import { clearArray } from './helpers';

const collection = [[], {}, "", null, undefined, NaN, "wee"];
const cleanCollection = collection.filter(clearArray);
//  ["wee"]
Collapse
 
myogeshchavan97 profile image
Yogesh Chavan

You're right. using Boolean directly makes code shorter and is really helpful. Some days back I had written an article describing the same with truthy and falsy values.