How to use reduce Method In Typescript
This approach employs a functional programming style with TypeScript’s reduce method. It iterates over the keys of the original dictionary, selectively adding key-value pairs to the filtered dictionary based on specified conditions.
Syntax:
const filteredDictionary = Object.keys(originalDictionary).reduce((acc, key) => {
if (typeof originalDictionary[key] === 'string') {
acc[key] = originalDictionary[key];
}
return acc;
}, {} as Record<string, any>);
Example:
const originalDictionary: Record<string, any> = {
name: 'w3wiki',
est: 2009,
city: 'Noida'
};
const filteredDictionary = Object.keys(originalDictionary).reduce((acc, key) => {
if (typeof originalDictionary[key] === 'string') {
acc[key] = originalDictionary[key];
}
return acc;
}, {} as Record<string, any>);
console.log(filteredDictionary);
Output:
{
name: "w3wiki",
city: "Noida"
}
Filter a Dictionary by Key or Value in TypeScript
Filtering a dictionary by key or value is a common task in TypeScript when working with data structures. TypeScript provides various approaches to achieve this efficiently.
Table of Content
- Using Object.keys() and Array.filter()
- Using Object.entries() and Array.filter()
- Using the for…in loop
- Using reduce Method
Contact Us