Implement a function compact(array) that creates an array with all falsey values removed. The values false, null, 0, '', undefined, and NaN are falsey (you should know this by heart!).
array (Array): The array to compact.(Array): Returns the new array of filtered values.
compact([0, 1, false, 2, '', 3,null]); // => [1, 2, 3]
compact(['hello', 123, [], {}]); // => ['hello', 123, [], {}]
Solution
/**
* @param {Array} array: The array to compact.
* @return {Array} Returns the new array of filtered values.
*/
export default function compact(array) {
const result = [];
for (let i = 0; i < array.length; i++) {
const value = array[i];
// Skip falsey values
if (value) {
result.push(value);
}
}
return result;
}
Here's a simpler solution that leverages Array.prototype.filter.
Open files in workspace
/**
* @param {Array} array: The array to compact.
* @return {Array} Returns the new array of filtered values.
*/
exportdefaultfunction compact(array) {
return array.filter(Boolean);
}