Open In App

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

Last Updated : 13 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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,

  • Sorting the keys of the original object using Object.keys() and sort().
  • Iterating over the sorted keys using reduce().
  • Creating a new object with sorted keys and corresponding values from the original object.

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 }.

Javascript




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 }.

Javascript




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 }


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads