One way to use the findIndex
function from the Underscore library in TypeScript is by first importing it:
index.ts40 chars2 lines
Then, assuming you have an array of objects, you can use the findIndex
function to search for the index of an object that meets a certain condition. For example, let's say you have an array of Person
objects defined like this:
index.ts172 chars11 lines
You could use the findIndex
function to find the index of the first person in the array who is over 30 years old:
index.ts60 chars2 lines
In this case, the index
variable would be set to 2, because the third person in the array (Charlie) is the first one who meets the condition. If no object in the array meets the condition, findIndex
returns -1
.
Note that the second argument to findIndex
is a callback function that takes an element of the array as its parameter and returns a boolean value indicating whether the element meets the condition. In this example, the callback function uses an arrow function expression to check whether the person's age is greater than 30.
gistlibby LogSnag