Sort Array of Objects by Property with Undefined Values in TypeScript
Last Updated :
02 May, 2024
In TypeScript, sorting an array of objects by property with undefined values by comparing the defined values precedes those with the undefined ones.
Below are the approaches to sort the array of objects by property with undefined values in TypeScript:
Using Array.reduce and findIndex method
In this approach, we are using the Array.reduce() method to iterate over the original array and construct a new array (acc) in sorted order based on the "rank" property. The findIndex function is used to determine the correct position for inserting the current item, considering undefined values, resulting in a sorted array by " " with items having defined ranks first and those with rank: undefined.
Syntax:
array.reduce((accumulator, currentValue, index, array) => {/* code*/}, initialValue);
array.findIndex((element, index, array) => {/* code*/});
Example: The below example uses the Array.reduce method to Sort an array of objects by property with undefined values in TypeScript.
JavaScript
interface Obj {
name: string;
rank?: number;
}
const data: Obj[] = [
{ name: 'DSA', rank: 3 },
{ name: 'Python', rank: 1 },
{ name: 'React', rank: undefined },
{ name: 'TypeScript', rank: 2 },
];
const res = data.reduce < Obj[] > ((acc, item) => {
const index = acc.findIndex(temp =>
(
item.rank === undefined
&&
temp.rank === undefined
)
||
(
item.rank !== undefined
&&
temp.rank !== undefined
&&
item.rank < temp.rank
)
);
if (index === -1) {
acc.push(item);
}
else {
acc.splice(index, 0, item);
}
return acc;
}, []);
console.log(res);
Output:
[{
"name": "Python",
"rank": 1
}, {
"name": "TypeScript",
"rank": 2
}, {
"name": "DSA",
"rank": 3
}, {
"name": "React",
"rank": undefined
}]
Using the Array.sort method
In this approach, we are using the Array.sort method to sort an array of objects by the "rank" property. We first map each object to include its original index, then perform the sorting based on the numeric value of "rank" (undefined as Infinity), followed by the original index. Finally, we map back to the original objects to get the sorted array with items having defined ranks first, and those with rank: undefined.
Syntax:
array.sort((a, b) => a - b);
Example: The below example uses the Array.sort method to Sort an array of objects by property with undefined values in TypeScript.
JavaScript
interface Obj {
name: string;
rank?: number;
}
const data: Obj[] = [
{
name: 'DSA',
rank: 3
},
{
name: 'Python',
rank: 1
},
{
name: 'React',
rank: undefined
},
{
name: 'TypeScript',
rank: 2
},
];
const res = data
.map((item, index) => ({ index, item }))
.sort((a, b) => {
const aRank = a.item.rank !== undefined ? a.item.rank : Infinity;
const bRank = b.item.rank !== undefined ? b.item.rank : Infinity;
return aRank - bRank || a.index - b.index;
})
.map(entry => entry.item);
console.log(res);
Output:
[{
"name": "Python",
"rank": 1
}, {
"name": "TypeScript",
"rank": 2
}, {
"name": "DSA",
"rank": 3
}, {
"name": "React",
"rank": undefined
}]
Using Array.prototype.sort method with custom comparison
In this approach, we'll use the Array.prototype.sort method to sort the array of objects by the "rank" property. We'll customize the comparison function to handle undefined values by treating them as the highest possible value. This ensures that objects with defined ranks precede those with undefined ranks.
Example: Below is the implementation using the Array.prototype.sort method.
JavaScript
interface Obj {
name: string;
rank?: number;
}
const data: Obj[] = [
{ name: 'DSA', rank: 3 },
{ name: 'Python', rank: 1 },
{ name: 'React', rank: undefined },
{ name: 'TypeScript', rank: 2 },
];
const sortedData = data.sort((a, b) => {
const aRank = a.rank !== undefined ? a.rank : Infinity;
const bRank = b.rank !== undefined ? b.rank : Infinity;
return aRank - bRank;
});
console.log(sortedData);
Output:
[{
"name": "Python",
"rank": 1
}, {
"name": "TypeScript",
"rank": 2
}, {
"name": "DSA",
"rank": 3
}, {
"name": "React",
"rank": undefined
}]
Similar Reads
Sort array of objects by string property value in JavaScript
Sorting arrays of objects based on a string property can be helpful for handling user data or dynamic lists. Here are different ways to sort an array of Objects By String Property Value. 1. Using localeCompare() Method â Most UsedThe JavaScript localeCompare() method returns a number indicating whet
3 min read
How to Sort an Array of Objects with Null Properties in TypeScript ?
Sorting an array of objects in TypeScript involves arranging objects based on specified properties. When dealing with null properties, ensure consistency by placing them either at the start or end of the sorted array to maintain predictability in sorting outcomes. Below are the approaches used to so
5 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
3 min read
How to sort an array of objects by property values ?
In this article, we will try to understand how to sort an array of objects by property values in JavaScript with the help of certain examples. Pre-requisite: Array of Objects in JavaScript Example: Input:[ { name: "Ram", age: 17 }, { name: "Mohan", age: 30 }, { name: "Shyam", age: 15 }, { name: "Shy
4 min read
How to Sort an Array of Objects by String Property value in Angular ?
An Object is a collection of properties, and a property is an association between a name (or key) and a value. A property's value can be a function, in which case the property is known as a method. In this article, we will learn how to Sort an array of objects by string property value in Angular. He
3 min read
Sort an array of objects in typescript?
We can achieve the sorting in TypeScript using the sort() function which is an inbuilt TypeScript function that is used to sort the elements of an array. Below are a few examples showing the sorting in TypeScript. Example 1: In this example, we will learn how to use the sort function to sort the arr
3 min read
How to get the Index of an Array based on a Property Value in TypeScript ?
Getting the index of an array based on a property value involves finding the position of an object within the array where a specific property matches a given value. The below approaches can be used to accomplish the task. Table of Content Using Array.findIndex()Using reduce() methodUsing for loopUsi
4 min read
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 Map
4 min read
How to Derive Union Type From Tuple/Array Values in TypeScript ?
This article will show how to derive union type from tuple/array values in TypeScript language. The union type in TypeScript is mainly formed by combining multiple types. We will see various approaches through which we can derive union type. Below are the possible approaches: Table of Content Using
2 min read
How to Sort Objects in an Array Based on a Property in a Specific Order in TypeScript ?
Sorting objects in an array based on a specific property is a common task in software development. TypeScript, with its static typing and powerful features, provides various approaches to accomplish this task efficiently. The below approaches can be used to sort an array of objects in properties. Ta
3 min read