How to Sort an Array of Objects with Null Properties in TypeScript ? - GeeksforGeeks (2024)

Last Updated : 11 Jun, 2024

Improve

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 sort an array of objects with null properties in TypeScript:

Table of Content

  • Using Array.prototype.sort with a ternary operator
  • Using Array.prototype.reduce
  • Using Array.prototype.filter() and concat()
  • Using Array.prototype.sort with a custom comparison function
  • Using Type Assertions

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"
}]

Approach 5: Using Type Assertions

Using type assertions to sort an array with null properties involves asserting the property as a defined type and providing a default value if it is null. This ensures TypeScript treats the property as defined for comparison.

Example

JavaScript
interface Item { name?: string | null; value?: number | null;}const items: Item[] = [ { name: 'item1', value: 10 }, { name: 'item2', value: null }, { name: null, value: 5 }, { name: 'item3', value: 15 },];items.sort((a, b) => { return (a.value ?? 0) - (b.value ?? 0);});console.log(items);

Output:

[
{ name: 'item2', value: null },
{ name: null, value: 5 },
{ name: 'item1', value: 10 },
{ name: 'item3', value: 15 }
]


kohliami558i

Improve

Next Article

How to Sort an Array Having Optional Properties in TypeScript ?

Please Login to comment...

How to Sort an Array of Objects with Null Properties in TypeScript ? - GeeksforGeeks (2024)

References

Top Articles
2023 Women's Soccer Schedule
2024 Women's Soccer Roster
Risen Kaiser Horns
Palmbeachschools Jobs
24 Hour Car Wash Queens Ny
Denman Promo Code
Ms Ortencia Alcantara Instagram
411.Com Reverse Address Lookup
Netlearning Login Rwjbh
Bekijk hier het rouwregister van Uitvaartzorg FSK
Target Nytimes
Nextdoor Myvidster
Haunted Mansion Showtimes Near Roxy Lebanon
Havasu Lake residents boiling over water quality as EPA assumes oversight
Maximise Your Funding: Key Insights on Accounting for Grants
Taxi Driver Kdrama Dramacool
Bowser's Fury Coloring Page
Battlenet We Couldn't Verify Your Account With That Information
Fabric Dynamic Lights
Tethrd Coupon Code The Hunting Public
Minneapolis, MN Real Estate & Homes for Sale | realtor.com®
What tools do you recommend for emceeing?
Emmi Sellers Cheerleader
Wirrig Pavilion Seating Chart
Chatzy Spanking
Clarkson Eyecare hiring Optometrist - Fredericksburg, VA in Fredericksburg, VA | LinkedIn
Sour Animal Strain Leafly
Funny Shooter Unblocked
Lenscrafters Westchester Mall
Runescape Abyssal Beast
Restored Republic June 16 2023
Deleon Malik Taylor-Griffin
Raya And The Last Dragon Voice Cast: Who's Voicing Each Character
Shannon Sharpe Pointing Gif
Educational Outfitters Denver
Emily Dealy Obituary
Get Over It Stables
Did You Hear About Worksheet Answers Page 211
Grupos De Cp Telegram
Okeeheelee Park Pavilion Rental Prices
Grayson County Craigslist
Ten Conservative Principles
marie claire Australia January 2016 Robyn Lawley, Rachel Taylor, Sarah Snook • EUR 11,50
The Little Mermaid (2023) | Rotten Tomatoes
Richard Sambade Obituary
55Th And Kedzie Elite Staffing
Autozone On 7 Mile And Hubbell
100.2华氏度是多少摄氏度
Rush Copley Swim Lessons
Siôn Parry: The Welshman in the red of Canada
German police arrest 25 suspects in plot to overthrow state – DW – 12/07/2022
Latest Posts
Article information

Author: Ray Christiansen

Last Updated:

Views: 5880

Rating: 4.9 / 5 (49 voted)

Reviews: 80% of readers found this page helpful

Author information

Name: Ray Christiansen

Birthday: 1998-05-04

Address: Apt. 814 34339 Sauer Islands, Hirtheville, GA 02446-8771

Phone: +337636892828

Job: Lead Hospitality Designer

Hobby: Urban exploration, Tai chi, Lockpicking, Fashion, Gunsmithing, Pottery, Geocaching

Introduction: My name is Ray Christiansen, I am a fair, good, cute, gentle, vast, glamorous, excited person who loves writing and wants to share my knowledge and understanding with you.