Implement a compactObject function
compactObject
is a utility function which can take nested objects and arrays and remove any falsy
values from them.
The values false
, null
, ''
, undefined
, 0
and NaN
are considered falsy.
1. Basic implementation
Do not mutate the original array. Consider only JSON serializable values will be passed to input.
function compactObject(input) { // other values if (typeof input !== 'object' && input && input != null) { return input; }
// for arrays if (Array.isArray(input)) { const outArr = []; input.forEach((item) => { if (item) { outArr.push(compactObject(item)); } }); return outArr; }
// for objects const outObj = {}; for (const key in input) { // Avoid iteration of inherited keys if (Object.hasOwn(input, key)) { const value = input[key];
// only when truthy if (value) { if (typeof value !== 'object') { outObj[key] = value; } else { outObj[key] = compactObject(value); } } } }
return outObj;}
const input = [0, 1, NaN, null, '', false, [{ name: 'John Doe', age: null, messages: ['Hi', ''] }]];
const output = compactObject(input);
/** * Yields: * [ 1, [ { "name": "John Doe", "messages": [ "Hi" ] } ]] */console.log(output);
Further Reading
I strongly encourage you to explore and tackle additional questions in my Recursion Questions for Frontend Interviews blog series.
By doing so, you can enhance your understanding and proficiency with recursion, preparing you to excel in your upcoming frontend interviews.
Wishing you best. Happy Interviewing 🫡.