Table of Contents#
- Introduction
- What is
_.compact()? - Syntax and Parameters
- Example Usage
- How
_.compact()Works Internally - Common Use Cases
- Best Practices
- Comparison with Native JavaScript
- Potential Pitfalls
- Combining with Other Underscore.js Functions
- References
What is _.compact()?#
The _.compact() function takes an array as input and returns a new array with all falsy values removed. In JavaScript, falsy values are:
falsenull0(numeric zero)""(empty string)undefinedNaN(Not a Number)
This function is invaluable for cleaning up arrays by eliminating values that are considered "empty" or "non-meaningful" in your use case.
Syntax and Parameters#
The syntax for _.compact() is straightforward:
_.compact(array)- Parameter:
array(required): The input array from which falsy values will be removed.
Example Usage#
Let’s explore practical examples to understand how _.compact() works.
Example 1: Basic Array Cleanup#
Remove falsy values from a mixed array:
const _ = require('underscore'); // Import Underscore.js (Node.js)
const mixedArray = [0, 1, false, 2, '', 3, null, undefined, NaN];
const cleanedArray = _.compact(mixedArray);
console.log(cleanedArray);
// Output: [1, 2, 3]Example 2: Form Input Sanitization#
Suppose you collect user tags from a form, where some inputs might be empty. Use _.compact() to clean the array:
const userTags = ['javascript', '', 'underscore', null, 'webdev'];
const validTags = _.compact(userTags);
console.log(validTags);
// Output: ['javascript', 'underscore', 'webdev']Example 3: API Response Processing#
Clean an array of user preferences (from an API) that contains empty or invalid entries:
const apiResponse = [
{ preference: 'dark mode' },
{ preference: null },
{ preference: '' },
{ preference: 'notifications' }
];
// Extract preferences and clean
const preferences = _.chain(apiResponse)
.pluck('preference') // Extract 'preference' values
.compact() // Remove falsy values
.value();
console.log(preferences);
// Output: ['dark mode', 'notifications']How _.compact() Works Internally#
At its core, _.compact() filters the input array to include only truthy values (values that evaluate to true when converted to a boolean).
Conceptually, it works like this (simplified implementation):
function compact(array) {
return array.filter(element => !!element); // Convert to boolean; truthy = true
}Underscore’s actual implementation handles edge cases (e.g., non-array inputs) but follows this core logic: iterate over the array and keep only elements that are truthy.
Common Use Cases#
_.compact() shines in scenarios where you need to:
- Sanitize User Input: Clean arrays of form values (e.g., tags, multiple selections) by removing empty strings or
null. - Process API Data: Remove empty or invalid entries from API responses (e.g.,
nullpreferences, empty strings). - Preprocess Arrays: Prepare arrays for operations like
_.sum()or_.map()by ensuring only valid (truthy) values exist.
Best Practices#
To use _.compact() effectively:
- Use When Falsy Values Are Unwanted: Only use
_.compact()if you explicitly want to remove all falsy values. If your array contains meaningful falsy values (e.g.,0as a valid score), this function will remove them (leading to bugs). - Chain with Other Functions: For complex workflows, chain
_.compact()with other Underscore functions (e.g.,_.map(),_.reduce()) using_.chain(). - Performance: For very large arrays, test performance. If needed, use native
Array.filter()(it’s often faster in modern JavaScript).
Comparison with Native JavaScript#
In modern JavaScript, you can replicate _.compact() using the native Array.filter() method with the Boolean constructor:
const mixedArray = [0, 1, false, 2, '', 3, null, undefined, NaN];
const cleanedArray = mixedArray.filter(Boolean);
console.log(cleanedArray); // [1, 2, 3]This works because Boolean converts its argument to a boolean: truthy values return true (so they are kept), and falsy values return false (so they are removed).
Potential Pitfalls#
Be cautious of these edge cases:
- Unintended Removal of Valid Falsy Values: Values like
0(e.g., a score of 0) or empty strings (e.g., a user’s middle name) will be removed. Verify your data doesn’t contain meaningful falsy values before using_.compact(). - Non-Array Inputs: Passing a non-array (e.g., an object, string) to
_.compact()can lead to unexpected results (e.g., a string is treated as an array of characters). Ensure the input is an array.
Combining with Other Underscore.js Functions#
Underscore supports method chaining (via _.chain()) to combine multiple functions. For example:
const data = [null, 10, 'hello', '', 20, undefined];
const result = _.chain(data)
.compact() // Remove falsy values
.map(x => typeof x === 'string' ? x.toUpperCase() : x * 2) // Transform
.value(); // Get the final array
console.log(result); // [20, 'HELLO', 40]References#
- Underscore.js Official Documentation -
_.compact - MDN Web Docs - Falsy Values in JavaScript
- MDN Web Docs -
Array.filter()
Conclusion#
The _.compact() function is a powerful tool for cleaning arrays by removing falsy values. By understanding its syntax, use cases, and best practices, you can streamline data processing, sanitize inputs, and write cleaner, more maintainable code. Whether you use Underscore.js or native JavaScript, the ability to remove falsy values is essential for robust array manipulation.
Happy coding! 🚀