How to Sort an Array of Objects with Null Properties in TypeScript ?
Last Updated :
03 May, 2024
Sorting an array of objects with null properties in TypeScript involves arranging its elements based on non-null properties.
Below are the approaches used to sort an array of objects with null properties in TypeScript:
Approach 1: Using Array.prototype.sort with a ternary operator
In this approach, we Sort an array of objects with null properties using Array.prototype.sort and a ternary operator for comparison. Prioritizes sorting based on existing properties or default sorting criteria if properties are null.
Example: Here, we sort arr based on the name. Objects with non-null name properties are sorted alphabetically, and null properties are sorted by id.
Javascript
interface MyObject {
id: number;
name?: string;
}
const arr: MyObject[] = [
{ id: 3, name: "Rohit" },
{ id: 1, name: "Amit" },
{ id: 2, name: "Rahul" }
];
const result = arr.sort((a, b) => (a.name && b.name) ?
a.name.localeCompare(b.name) :
(a.name ? -1 : b.name ? 1 : a.id - b.id));
console.log(result);
Output:
[
{ id: 1, name: 'Amit' },
{ id: 2, name: 'Rahul' },
{ id: 3, name: 'Rohit' }
]
Approach 2: Using Array.prototype.reduce
In this approach we uses Array.prototype.reduce with a custom sorting function. It iterates over elements, inserting them into a sorted array based on their properties. Handles cases where properties are null.
Example: Here, we Sorts arr based on name. Uses Array.prototype.reduce with functional programming to insert elements into a new array at the correct position. Prints the result.
Javascript
interface MyObject {
id: number;
name?: string;
}
const arr: MyObject[] = [
{ id: 3, name: "Rohit" },
{ id: 1, name: "Amit" },
{ id: 2, name: "Rahul" }
];
const result =
arr.reduce((acc: MyObject[], curr: MyObject) => {
const index = acc.findIndex((obj: MyObject) => {
if (curr.name && obj.name) {
return curr.name.localeCompare(obj.name) < 0;
} else {
return !obj.name;
}
});
return index !== -1
? [...acc.slice(0, index), curr, ...acc.slice(index)]
: [...acc, curr];
}, []);
console.log(result);
Output:
[
{ id: 1, name: 'Amit' },
{ id: 2, name: 'Rahul' },
{ id: 3, name: 'Rohit' }
]
Approach 3: Using Array.prototype.filter() and concat()
Filter out objects with null properties, sort the remaining objects based on their non-null property, then concatenate them with objects having null properties to maintain original order.
Example: In this example we filter out objects with defined names, sorts them by name, then concatenates them with objects having undefined names, resulting in the sorted array.
JavaScript
interface MyObject {
id: number;
name?: string;
}
const arr: MyObject[] = [
{ id: 3, name: "Rohit" },
{ id: 1, name: "Amit" },
{ id: 2, name: "Rahul" }
];
const sortedArray = arr
// Filter out objects with undefined names
.filter(obj => obj.name !== undefined)
// Sort by name
.sort((a, b) => a.name!.localeCompare(b.name!))
// Concatenate with objects having undefined names
.concat(arr.filter(obj => obj.name === undefined));
console.log(sortedArray);
Output:
[
{ id: 1, name: 'Amit' },
{ id: 2, name: 'Rahul' },
{ id: 3, name: 'Rohit' }
]
Approach 4: Using Array.prototype.sort with a custom comparison function
In this approach, we’ll use Array.prototype.sort with a custom comparison function that handles cases where properties are null or undefined. This approach provides flexibility in defining sorting criteria and can handle various scenarios efficiently.
Example: Here, we sort arr based on the id property. Objects with non-null id properties are sorted numerically, and objects with null or undefined id properties are moved to the end of the array while preserving their original order.
JavaScript
interface MyObject {
id?: number;
name?: string;
}
const arr: MyObject[] = [
{ id: 3, name: "Rohit" },
{ name: "Amit" },
{ id: 1, name: "Nikunj" },
{ id: 2, name: "John" },
{ name: "Smith" }
];
const result = arr.sort((a, b) => {
if (a.id !== undefined && b.id !== undefined) {
return a.id - b.id;
} else if (a.id !== undefined) {
return -1;
} else if (b.id !== undefined) {
return 1;
} else {
// If both objects have undefined id properties,
// compare based on name property
return (a.name || '').localeCompare(b.name || '');
}
});
console.log(result);
Output:
[{
"id": 1,
"name": "Nikunj"
}, {
"id": 2,
"name": "John"
}, {
"id": 3,
"name": "Rohit"
}, {
"name": "Amit"
}, {
"name": "Smith"
}]
Share your thoughts in the comments
Please Login to comment...