How to use Array.reduce and findIndex method In Typescript
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.
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
}]
Sort Array of Objects by Property with Undefined Values in TypeScript
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:
Table of Content
- Using Array.reduce and findIndex method
- Using the Array.sort method
- Using Array.prototype.sort method with custom comparison