Jump to the editorJAVASCRIPT
JAVASCRIPT JAVASCRIPT JAVASCRIPT
4.2. Remove falsy values
Easy
Topics
This question is in
4. Array utilitiesLists built from optional parts collect gaps: a class list where some classes are false because a condition did not hold, a row of form values where empty fields are "", an API response where missing ids came back as null. Before the list is joined or shown, the empty values have to go.
Write compact(array) in compact.js. It returns a new array with every falsy value removed and every other value kept, in order.
Signature
function compact(array) // returns a new arrayarray: the items to filter. It is not changed.- Returns a new array, even when nothing was removed.
Requirements
- It removes
false,null,undefined,0,""andNaN. - It also removes
-0and the BigInt0n. - It keeps every truthy value, in the original order.
- It keeps strings that only look false, such as
"0","false"and" ". - It keeps empty arrays, empty objects, negative numbers and
Infinity. - It keeps a boxed value such as
new Boolean(false): an object is always truthy. - Holes in the input are dropped, and the result has no holes.
- An empty array, or an array of only falsy values, gives
[]. - The result is a new array; the input is not changed; objects are kept as they are, not copied.
- It handles 100,000 items quickly.
Examples
compact([0, 1, false, 2, "", 3]); // [1, 2, 3]
compact(["a", null, undefined, NaN]); // ["a"]compact(["0", "false", [], {}]); // ["0", "false", [], {}]
compact([-0, 0n, -1]); // [-1]compact([1, , 2]); // [1, 2]: the hole is gone
compact([]); // []Environment
- Plain JavaScript in a browser page; the tests call the global
compactfromcompact.js. - Any built-in may be used.
Hints
- Do you need to list the falsy values one by one, or can JavaScript tell you whether a value is falsy?
- Is
"0"a number?
The explanation comes with the course
A walkthrough of every line of a solution, the mistakes the tests catch, other ways to write it, and links to the lessons that teach each idea.
- Every line explained
- The mistakes each test catches
- Links to the lessons behind it
Back to the question
Loading the editor…