HarmonyOS arktoolbox compact: Remove Falsy Array Values in One Line
This article introduces the compact utility from the arktoolbox library for HarmonyOS, which removes falsy values (null, undefined, 0, false, empty string, NaN) from arrays, explains its implementation, compares it with filter(Boolean), highlights edge cases like 0 being valid data, and demonstrates practical usage in forms, API aggregation, and caching.
Problem: Falsy Values Break ForEach Rendering
When building HarmonyOS UIs, list data sources often contain "fake data" — null, empty strings, 0, or false — that cause blank rows, crashes, or weird placeholders when fed into ForEach. Native ArkTS lacks a built-in falsy-filter method, so developers either write array.filter(Boolean) or manual for loops. However, filter(Boolean) also removes 0 and '', which may be legitimate business data.
Solution: arktoolbox compact
The compact function from the open-source arktoolbox library (200+ utilities, install via ohpm install arktoolbox) explicitly wraps this cleanup: pass an array that may contain falsy values, get back a new array with only truthy elements.
Method Signature & Source Code
export function compact<T>(array: (T | undefined | null | false | '' | 0)[]): T[] {
const length = array.length;
if (length === 0) {
return [];
}
const result: T[] = [];
for (let i = 0; i < length; i++) {
const value = array[i];
if (value) {
result.push(value);
}
}
return result;
}Two details worth noting:
Generic signature lists all possible falsy types in the parameter type, so the compiler signals this is a dirty-data cleaner.
Empty-array fast path returns [] before looping, saving a needless traversal on large datasets.
The core filter is if (value). ArkTS implicit Boolean(value) conversion matches JavaScript: false, null, undefined, 0, '' (empty string) are falsy; everything else is truthy.
Tip: compact uses truthy check, so numeric 0 is treated as falsy and removed. If 0 is valid business data (e.g., inventory count, price), do not use compact blindly; instead use filter with a custom predicate like x => x !== null && x !== undefined .
Parameters & Return Value
array : (T | undefined | null | false | '' | 0)[] — Source array that may contain falsy values
Return : T[] — New array with only truthy elements; original array unchanged
The return type strips the falsy union, leaving clean T[]. This matters for downstream ForEach or pure functions — you get a "definitely has values" array without extra null checks.
Comparison with filter(Boolean)
Both produce identical results for typical dirty-data cleaning. The difference is intent visibility: compact makes the rule explicit via its name and type signature; readers don't need to recall which values Boolean coerces to false.
Both also drop NaN (falsy in truthy check). Since NaN !== NaN, a manual === filter would miss it; compact handles this automatically.
const dirty = [1, NaN, 0, '', null, 2];
const a = compact(dirty); // [1, 2]
const b = dirty.filter(Boolean); // [1, 2], same resultDemo Cases (CompactDemo.ets)
The demo component includes six preset cases and an interactive playground:
Case 1 Classic: [0, 1, false, 2, '', 3] → [1, 2, 3] (0, false, '' removed)
Case 2 All Falsy: [false, null, 0, '', undefined] → [] Case 3 All Truthy: [1, 'hello', true] → unchanged
Case 4 String Filter: ['a', '', 'b', '', 'c'] → ['a', 'b', 'c'] Case 5 Mixed Numbers & Falsy: [0, 1, false, 2, '', 3, null, 4] → [1, 2, 3, 4] Case 6 Boolean Mix: [true, false, true, true, false] → [true, true, true] (shows true is kept, false removed — symmetric with 1 / 0)
Rule of thumb: only the six falsy values ( false, null, 0, '', undefined, NaN) are removed; everything else stays.
Real-World Usage
Form handling: Multi-select components may leave undefined in bound arrays; compact cleans before render.
API aggregation: Merge multiple sources, some returning null; compact then map for field extraction: compact(rawList).map(item => item.name).
Cache reads: Expired keys return null; compact yields valid objects directly, avoiding per-item null checks in render.
Remember the caveat: when 0 is meaningful data, use a custom filter instead.
Summary
compactturns the tedious "filter falsy" chore into a one-liner with behavior matching JS truthy rules. Its real value isn't saving a few lines — it's making intent crystal clear. Seeing compact(arr) tells readers instantly "cleaning falsy values here," no need to decipher a callback.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
51CTO HarmonyOS Developer Community
The HarmonyOS Developer Community is a learning-oriented community for developers to learn, communicate, ask questions, and share.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
