This tutorial will explain the way to group an array of objects by key in TypeScript.
How to Group Array of Objects by Key in TypeScript?
Use the “reduce()” method for grouping an array of objects by key. The reduce() method in TypeScript is a higher-order function that deals with arrays. It is used to iterate over the array of elements and reduce them into a single value. The single value will be anything such as a string, an array, a number, or an object. The reduce() method is similar to the reduce() function in JavaScript.
Syntax
The reduce() method takes two arguments, a callback function, and an initial value:
In the above syntax
- The “callbackFunc” is the function that executes on every array element. It takes two arguments, an “accumulator” known as “previousValue” and the “current element” that is being iterated over. The accumulator is the returned value of the previous function call/iteration.
- The “initialValue” is an optional argument and it specifies the initial value of the previousValue parameter. If initialValue is not provided, the previousValue parameter will be set to the first element of the array and the currentValue parameter will be set to the second element of the array.
Example
Create an “interface” named “Info” with two properties “name” and “age” in a TypeScript file named “arrayofObjects.ts”:
name: string;
age: number;
}
Create an array of type “Info” using the interface and add objects as array elements:
{ name: "Mili", age: 22 },
{ name: "Lilac", age: 26 },
{ name: "Micheal", age: 22 },
{ name: "Jack", age: 26 },
{ name: "John", age: 32 },
{ name: "Jenny", age: 26 },
{ name: "Stephen", age: 32}
];
Call the reduce() method to iterate over each object in the array and group them by their property “age” using an object called group. Within the reduce function, first, we will check whether the “age” of the current object is already in the group object or not. If it is not, create a new empty array for that key in the group object. Then, push the current object to the corresponding array in the group object. After iterating over all the objects in “Info”, the grouped object will contain each key in “info” as a property, with the value being an array of all the objects with the key “age”:
if (!group[item.age]) {
group[item.age] = [];
}
group[item.age].push(item);
return group;
}, {});
Lastly, print the array of objects on the console:
Now, transpile the TypeScript file, using the given command:
Finally, execute the JavaScript file with the help of the below command:
Output
That’s all about grouping an array of objects using their keys in TypeScript.
Conclusion
For grouping an array of objects by key, utilize the “reduce()” method. It iterates over the array of elements and reduces them into a single value which can be a string, number, array, or object. This tutorial explained the method to group an array of objects by key in TypeScript.