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 }


Similar Reads

How to Declare Object Value Type Without Declaring Key Type in TypeScript ?
We will create an object value type without declaring the key type. We can not directly define the type of value we will use different methods for declaring the object value type. These are the following methods for declaring the object value type: Table of Content Using Record Utility TypeUsing Mapped TypesUsing GenericsBy utilizing Indexed TypesA
3 min read
How to Get an Object Value By Key in TypeScript
In TypeScript, we can get an object value by key by accessing the specific properties within the objects of the dynamic type. This can be done using Dot Notation, Bracket Notation, and Optional Chaining. In this article, we will explore all these approaches along with their implementation in terms of examples and outputs. Table of Content Using Dot
3 min read
How to Remove a Key from TypeScript Object ?
In TypeScript, objects are mutable, which means you can modify them by adding, updating, or removing properties. Removing a key from an object involves either creating a new object without the specified key or using certain built-in methods to achieve the desired result. Below are the approaches used to remove a key from TypeScript object: Table of
3 min read
How to Merge Child Object Value to Parent Key Based on Key Name in JavaScript ?
JavaScript allows us to merge values from child objects into their parent object based on a specific key name. This can be useful for organizing data or simplifying complex structures. There are several approaches available in JavaScript to merge child object values to parent key based on the key name which are as follows. Table of Content Using fo
3 min read
How to Initialize a TypeScript Object with a JSON-Object ?
To initialize a TypeScript Object with a JSON-Object, we have multiple approaches. In this article, we are going to learn how to initialize a TypeScript Object with a JSON-Object. Below are the approaches used to initialize a TypeScript Object with a JSON-Object: Table of Content Object.assign Type AssertionSpread OperatorClass InitializationUsing
3 min read
How to access an object having spaces in the object's key using JavaScript ?
Given an object and the task is to access the object in which the key contains spaces. There are a few methods to solve this problem which are discussed below: Approach 1: Create an object having space-separated keys.Use square bracket notation instead of dot notation to access the property. Example: This example implements the above approach. C/C+
2 min read
How to set an object key inside a state object in React Hooks?
We can update a React hooks state object that has a nested object containing objects with index keys with the following approach, Before doing so, consider the following example: Example: Following is the default state object: const [data, setData] = useState({ name:'', contact:'', address:{ 0:{}, 1:{}, } }) Following is the desired output after up
2 min read
How to Append an Object as a Key Value in an Existing Object in JavaScript ?
In JavaScript, An object is a key-value pair structure. The key represents the property of the object and the value represents the associated value of the property. In JavaScript objects, we can also append a new object as a Key-value pair in an existing object in various ways which are as follows. Table of Content Using JavaScript Spread (...) Ope
2 min read
How to Add Duplicate Object Key with Different Value to Another Object in an Array in JavaScript ?
Adding duplicate object keys with different values to another object in an array in JavaScript refers to aggregating values under the same key from multiple objects in an array, creating a new object where each key corresponds to an array of associated values. Table of Content Using for...of LoopUsing reduce()Using for...of LoopFor...of loop in Jav
2 min read
How to Sort an Array of Object using a Value in TypeScript ?
Sorting an array of objects using a value in TypeScript pertains to the process of arranging an array of objects in a specified order based on a particular property or value contained within each object. The below approaches can be used to sort an array of objects using a value in TypeScript: Table of Content Using the Array.prototype.sort()Using t
3 min read