JavaScript: Remove all falsy values from an object or array
JavaScript Array: Exercise-47 with Solution
Remove Falsey from Object or Array
Write a JavaScript program to remove all false values from an object or array.
- Use recursion.
- Initialize the iterable data, using Array.isArray(), Array.prototype.filter() and Boolean for arrays in order to avoid sparse arrays.
- Use Object.keys() and Array.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 typeof to determine if a given value is an object and call the function again to deeply compact it.
Sample Solution:
JavaScript Code :
Output:
{"c":true,"e":1,"g":"a","h":[true,1,"a"],"i":{"l":"a"}}
Flowchart :

Live Demo :
For more Practice: Solve these Related Problems:
- Write a JavaScript function that recursively removes all falsey values from an object and its nested arrays.
- Write a JavaScript function that filters an array to remove false, null, 0, "", undefined, and NaN values.
- Write a JavaScript function that traverses an object and deletes keys with falsey values, returning a cleaned object.
- Write a JavaScript function that generically removes falsey values from both arrays and objects, supporting nested structures.
Improve this sample solution and post your code through Disqus.
Previous: Permutations of an array elements.
.
Next: Check every numbers are prime or not in an array.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.