Typescript

How to Group Array of Objects by Key in TypeScript?

Programmers frequently need to group an array of objects by a particular key as it enables them to properly organize and manage data. For storing the grouped values in TypeScript, use the “reduce” method with an object. A new object that has each key as a property and associated values that are arrays of all the items with that key can be created by iterating over each object in the array and grouping them by their key property.

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:

reduce(callbackFnc, initialValue)

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”:

interface Info {
 name: string;
 age: number;
}

Create an array of type “Info” using the interface and add objects as array elements:

const info: Info[] = [
 { 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”:

const groupedKeys = info.reduce((group: {[key: string]: Info[]}, item) => {
 if (!group[item.age]) {
  group[item.age] = [];
 }
 group[item.age].push(item);
 return group;
}, {});

Lastly, print the array of objects on the console:

console.log(groupedKeys);

Now, transpile the TypeScript file, using the given command:

tsc arrayofObjects.ts

Finally, execute the JavaScript file with the help of the below command:

node arrayofObjects.js

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.

About the author

Farah Batool

I completed my master's degree in computer science. I am an academic researcher and love to learn and write about new technologies. I am passionate about writing and sharing my experience with the world.