Find the Length of a Dictionary in TypeScript
Last Updated :
04 Sep, 2024
In TypeScript, to find the length of a dictionary, there is no built-in property for objects that determines the length of the dictionary. The length of the input dictionary can be retrieved by counting the pairs of key values in it.
There are several approaches available in TypeScript for finding the length of a dictionary which are as follows:
Using Object.keys() function
In this approach, we are using the Object.keys()
function in TypeScript to extract an array of keys from the dictionary (dict
). By using the length
property to this array, we find the count of keys which is the length of the dictionary. The output res
variable stores the number of key-value pairs, and then prints to the console.
Syntax:
Object.keys(obj: object): string[];
Example: The below example uses the Object.keys() function to find the length of a dictionary in TypeScript.
JavaScript
const dict: Record<string, string> = {
'data structures': 'algorithms',
'programming languages': 'python',
'computer science': 'geeksforgeeks',
};
const res: number = Object.keys(dict).length;
console.log(res);
Output:
3
Using for...in Loop
In this approach, we are using a for...in loop in TypeScript to iterate through the enumerable properties (keys) of the dictionary (dict). For each iteration, the loop checks if the property is directly owned by the object using hasOwnProperty to exclude properties inherited from the prototype chain. If true, the res variable is incremented, and then final count is then printed to the console.
Syntax:
for (variable in object) {
// code
}
Example: The below example uses the for...in loop to find the length of a dictionary in TypeScript.
JavaScript
const dict: Record<string, string> = {
'data structures': 'algorithms',
'programming languages': 'python',
'computer science': 'geeksforgeeks',
};
let res: number = 0;
for (const key in dict) {
if (dict.hasOwnProperty(key)) {
res++;
}
}
console.log(res);
Output:
3
Using reduce() function
In this approach, the reduce() function is used on the array of keys obtained using Object.keys() to accumulate and count each key, starting with an initial value of 0. The output res variable stores the length of the dictionary, and it is then printed to the console.
Syntax:
array.reduce(callback: (accumulator: T, currentValue: T, currentIndex: number, array: T[]) => T,
initialValue?: T): T;
Example: The below example uses the reduce function to find the length of a dictionary in TypeScript.
JavaScript
const dict: Record<string, string> = {
'data structures': 'algorithms',
'programming languages': 'python',
'computer science': 'geeksforgeeks',
};
const res: number = Object
.keys(dict).
reduce((acc) => acc + 1, 0);
console.log(res);
Output:
3
Using Object.entries()
In this approach, we utilize the Object.entries() function to retrieve an array of key-value pairs from the dictionary (dict). We then determine the length of this array, which corresponds to the number of entries in the dictionary.
Syntax:
Object.entries(obj: object): [string, any][];
Example: This TypeScript code defines a dictionary `dict`, then calculates its length using `Object.entries()` and retrieves the number of key-value pairs. Finally, it logs the result.
JavaScript
const dict: Record<string, string> = {
'data structures': 'algorithms',
'programming languages': 'python',
'computer science': 'geeksforgeeks',
};
const res: number = Object.entries(dict).length;
console.log(res); // Output: 3
Output:
3
Using Object.values() Function
In this approach, we utilize the Object.values() function to extract an array of values from the dictionary (dict). By applying the length property to this array, we can determine the number of key-value pairs in the dictionary. The result is stored in the res variable and then printed to the console.
Example: The example below demonstrates how to use the Object.values() function to find the length of a dictionary in TypeScript.
JavaScript
// Define a dictionary with different types of values
const dict: Record<string, any> = {
'name': 'Alice',
'age': 30,
'isStudent': false,
'subjects': ['Math', 'Science'],
'address': {
city: 'Wonderland',
zipCode: '12345'
}
};
// Calculate the length of the dictionary using Object.values()
const lengthOfDict: number = Object.values(dict).length;
// Output the result
console.log(`The length of the dictionary is: ${lengthOfDict}`);
Output:
The length of the dictionary is: 5
Similar Reads
Nested Dictionary in TypeScript
TypeScript is a powerful, statically typed superset of JavaScript that offers robust features for building large-scale applications. One of its features is the ability to handle complex data structures, such as nested dictionaries. In this article, we'll explore what nested dictionaries are, how to
4 min read
How to Find the Length of JavaScript Dictionary ?
In JavaScript, you may often find a dictionary referred to as an object. Therefore, unlike arrays which have a length property, objects (dictionaries) do not have a built-in length property. However, the âlength" of a given dictionary in JavaScript may be determined through counting the pairs of key
3 min read
Find the Length Tuple in TypeScript ?
In TypeScript, a Tuple is the data structure that allows storing a fixed number of elements of different types in a specific order. We can find the length of a tuple using various approaches that are implemented in this article in terms of examples. There are several approaches available in TypeScri
3 min read
How to Declare a Fixed Length Array in TypeScript ?
To declare a Fixed-length Array in TypeScript you can use a Tuple. Tuple types allow you to specify the types for each element in the array and, importantly, define a fixed number of elements in a specific order. In this article, we are going to learn how to declare a fixed-length array in TypeScrip
3 min read
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 loopUsing red
3 min read
How to Remove Keys from a TypeScript Dictionary ?
In TypeScript, we can remove keys from a TypeScript Dictionary using various approaches that include deleting keywords, Object Destructuring, and by using Object.keys() and Array.reduce() methods. There are several approaches to removing keys from a TypeScript Dictionary which are as follows: Table
3 min read
How to get Value from a Dictionary in Typescript ?
In TypeScript, a dictionary consists of objects that store data in the key-value pairs, and allow retrieval of values based on the specified keys. We can get value from a dictionary for the specific keys using various approaches. Table of Content Using Dot NotationUsing Bracket NotationUsing a Funct
2 min read
How to Convert Typescript Dictionary to String ?
In TypeScript, dictionaries are often represented as the objects where keys are associated with the specific values. Converting a TypeScript dictionary to a string is an important task when doing API calls where we cast the JSON response from the API to a string. Below are the ways to convert a Type
4 min read
How to Sort a Dictionary by Value in TypeScript ?
In TypeScript, dictionaries are objects that store key-value pairs. Sorting a dictionary by value involves arranging the key-value pairs based on the values in ascending or descending order. The below approaches can be used to accomplish this task: Table of Content Using Object.entries() and Array.s
2 min read
How to Check if a Key Exists in a Dictionary in TypeScript ?
In TypeScript dictionaries are used whenever the data is needed to be stored in key and value form. We often retrieve the data from the dictionaries using an associated key. Therefore it becomes crucial to check whether the key exists in a dictionary or not. We can use the below methods to check if
4 min read