filter obj-array leaving only one object in typescript

To filter an array leaving only one object based on a certain condition, you can use the filter method in combination with slice:

index.ts
const arr = [{name: 'John', age: 25}, {name: 'Mary', age: 30}, {name: 'Peter', age: 22}];

const filteredArr = arr.filter(obj => obj.age === 25).slice(0,1);
157 chars
4 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