Open In App

How to Sort or Reduce an Object by Key in TypeScript ?

Sorting an object by key generally refers to arranging its properties in a specific order, while reducing involves selecting a subset of properties based on provided keys. Different approaches allow developers to perform these operations with flexibility.

Below are the approaches used to sort or reduce an object by key in TypeScript:



Sorting an Object by Key

This approach involves,



Example: Here, code sorts the keys of the unsortedObject object alphabetically. Then, it creates a new object sortedObject with the keys sorted in alphabetical order. The reduce() method iterates over the sorted keys, copying each key-value pair from unsortedObject to sortedObject. Finally, the sortedObject is logged to the console, resulting in { a: 1, b: 2, c: 3 }.




const unsortedObject = { c: 3, a: 1, b: 2 };
 
// Sort the keys
const sortedKeys = Object.keys(unsortedObject).sort();
 
// Create a new object with sorted keys
const sortedObject = sortedKeys.reduce((acc, key) => {
    acc[key] = unsortedObject[key];
    return acc;
}, {});
 
console.log(sortedObject);

Output:

{ a: 1, b: 2, c: 3 }

Reducing an Object by Key

Reducing an object by key involves creating a new object that contains only a subset of the original object’s key-value pairs. TypeScript allows us to achieve this using techniques such as filtering, mapping, or directly iterating over the keys and selectively copying key-value pairs.

Example: Here, code creates a new object reducedObject by selecting specific keys ('a' and 'c') from originalObject and copying their corresponding values. The result is logged to the console as { a: 1, c: 3 }.




const originalObject: Record<string, number> =
    { a: 1, b: 2, c: 3, d: 4 };
const selectedKeys: string[] = ['a', 'c'];
 
const reducedObject: Record<string, number> =
    selectedKeys.reduce((acc, key) => {
    acc[key] = originalObject[key];
    return acc;
}, {});
 
console.log(reducedObject); // Output: { a: 1, c: 3 }

Output:

{ a: 1, c: 3 }

Article Tags :