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.
Compact Object Algorithm
To deeply remove all falsy values from an object or array, use the following algorithm:
- Use recursion to call the
compactObject()function on each nested object or array. - Initialize the iterable data using
Array.isArray(),Array.prototype.filter(), andBoolean(). This is done to avoid sparse arrays. - Use
Object.keys()andArray.prototype.reduce()to iterate over each key with an appropriate initial value. - Use
Boolean()to determine the truthiness of each key's value and add it to the accumulator if it's truthy. - Use
typeofto determine if a given value is anobjectand 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.