Recursive Falsy Value Removal in JavaScript

JavaScriptJavaScriptBeginner
Practice Now

This tutorial is from open-source community. Access the source code

Introduction

In this lab, we will explore how to use recursion to deeply remove all falsy values from an object or array in JavaScript. We will create a function that takes an object or array as input and returns a new, compacted object or array with only truthy values. This technique can be useful for data cleaning and simplification in various programming applications.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL javascript(("`JavaScript`")) -.-> javascript/BasicConceptsGroup(["`Basic Concepts`"]) javascript(("`JavaScript`")) -.-> javascript/AdvancedConceptsGroup(["`Advanced Concepts`"]) javascript/BasicConceptsGroup -.-> javascript/variables("`Variables`") javascript/BasicConceptsGroup -.-> javascript/data_types("`Data Types`") javascript/BasicConceptsGroup -.-> javascript/arith_ops("`Arithmetic Operators`") javascript/BasicConceptsGroup -.-> javascript/comp_ops("`Comparison Operators`") javascript/BasicConceptsGroup -.-> javascript/cond_stmts("`Conditional Statements`") javascript/BasicConceptsGroup -.-> javascript/array_methods("`Array Methods`") javascript/AdvancedConceptsGroup -.-> javascript/higher_funcs("`Higher-Order Functions`") subgraph Lab Skills javascript/variables -.-> lab-28206{{"`Recursive Falsy Value Removal in JavaScript`"}} javascript/data_types -.-> lab-28206{{"`Recursive Falsy Value Removal in JavaScript`"}} javascript/arith_ops -.-> lab-28206{{"`Recursive Falsy Value Removal in JavaScript`"}} javascript/comp_ops -.-> lab-28206{{"`Recursive Falsy Value Removal in JavaScript`"}} javascript/cond_stmts -.-> lab-28206{{"`Recursive Falsy Value Removal in JavaScript`"}} javascript/array_methods -.-> lab-28206{{"`Recursive Falsy Value Removal in JavaScript`"}} javascript/higher_funcs -.-> lab-28206{{"`Recursive Falsy Value Removal in JavaScript`"}} end

Compact Object Algorithm

To deeply remove all falsy values from an object or array, use the following algorithm:

  1. Use recursion to call the compactObject() function on each nested object or array.
  2. Initialize the iterable data using Array.isArray(), Array.prototype.filter(), and Boolean(). This is done to avoid sparse arrays.
  3. Use Object.keys() and Array.prototype.reduce() to iterate over each key with an appropriate initial value.
  4. Use Boolean() to determine the truthiness of each key's value and add it to the accumulator if it's truthy.
  5. Use typeof to determine if a given value is an object and call the function again to deeply compact it.

Here's the code for the compactObject() function:

const compactObject = (val) => {
  const data = Array.isArray(val) ? val.filter(Boolean) : val;
  return Object.keys(data).reduce(
    (acc, key) => {
      const value = data[key];
      if (Boolean(value))
        acc[key] = typeof value === "object" ? compactObject(value) : value;
      return acc;
    },
    Array.isArray(val) ? [] : {}
  );
};

To use this function, pass an object or array as an argument to compactObject(). The function will return a new object or array with all falsy values removed.

For example:

const obj = {
  a: null,
  b: false,
  c: true,
  d: 0,
  e: 1,
  f: "",
  g: "a",
  h: [null, false, "", true, 1, "a"],
  i: { j: 0, k: false, l: "a" }
};
compactObject(obj);
// { c: true, e: 1, g: 'a', h: [ true, 1, 'a' ], i: { l: 'a' } }

Summary

Congratulations! You have completed the Compact Object lab. You can practice more labs in LabEx to improve your skills.

Other JavaScript Tutorials you may like