Arrays you build from real-world data — form fields, parsed query strings, joined query results — often end up sprinkled with null, undefined, empty strings, and the occasional NaN. Before you render or process the list, you want the gaps gone.
Implement compact(array), which returns a new array with every falsy value removed. This mirrors lodash's _.compact and is a common one-line interview warm-up that hides a subtle gotcha around the string "0".
function compact(array) {
// returns a new array containing only the truthy values from `array`,
// in their original order
}
compact([0, 1, false, 2, '', 3, null]);
// → [1, 2, 3]
compact(['hello', undefined, 'world', NaN, 0n, 'js']);
// → ['hello', 'world', 'js']
false, null, undefined, 0, NaN, "", and 0n — these all get stripped."0" stays — it's a non-empty string, which is truthy. Only the number 0 is falsy.compact([]) returns [].