A
arktype4w ago
Alan

Filtering Array<unknown> to a type?

Is this the best way to filter an Array of unknown to an ark type?:
type transaction = type(...);
const items: unknown[] = ...;
const transactions = items
.filter(transaction.allows)
.map(transaction);
type transaction = type(...);
const items: unknown[] = ...;
const transactions = items
.filter(transaction.allows)
.map(transaction);
I don't need to throw when something in items doesn't match. I just want to filter.
2 Replies
ssalbdivad
ssalbdivad3w ago
Generally flatMap is a good way to filter and map with a single function in JS:
const transactions = items.flatMap(item => {
const out = transaction(item)
return out instanceof type.errors ? [] : [out]
})
const transactions = items.flatMap(item => {
const out = transaction(item)
return out instanceof type.errors ? [] : [out]
})
Alan
AlanOP3w ago
Makes sense, thanks!

Did you find this page helpful?