DEV Community

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

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"]