To filter an array leaving only one object based on a certain condition, you can use the filter
method in combination with slice
:
index.ts157 chars4 lines
In this example, arr
is an array of objects with properties name
and age
. We want to filter the array based on the age
property and only keep the object(s) where age === 25
. We then use the slice
method to keep only one object from the filtered array. The result will be a new array with a single object that satisfies the filtering condition.
gistlibby LogSnag