The collect
function from the Underscore library is used to transform elements of an array using a provided iterator function. Here's an example in Typescript:
index.ts348 chars17 lines
In the example above, we import the Underscore library using the * as _
syntax. We define an interface for the items in our array, and then create an array of Item
objects.
The _.collect
function takes two parameters: the array to be transformed, and an iterator function. The iterator function takes an item from the array as its parameter and returns the transformed value. In this case, we're transforming each Item
object into its name
property.
The transformed values are then returned as a new array by the _.collect
function and assigned to the itemNames
variable. Finally, we log the itemNames
array to the console.
Overall, the collect
function is a powerful tool for transforming an array in a functional and concise way.
gistlibby LogSnag