Open In App

How to Sort an Array Having Optional Properties in TypeScript ?

Last Updated : 18 Apr, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Sorting an array with optional properties in TypeScript involves arranging its elements based on a primary property, with fallbacks to secondary properties or default sorting criteria if the primary property is absent.

Below are the approaches used to sort an array having optional properties in TypeScript:

Approach 1: Using the Array.prototype.sort

In this approach, we are using Array.prototype.sort with a custom comparator function to sort arrays with optional properties. Prioritize sorting based on optional properties, then fall to other criteria such as numerical values

Syntax:

arr.sort(compareFunction);

Example: Here, we are Sort arr by name property in ascending order, fallback to sorting by id. Handles cases where `name` is present or absent in MyObject interface.

Javascript
interface MyObject {
  id: number;
  name?: string;
}

const arr: MyObject[] = [
  { id: 3, name: "Rohit" },
  { id: 1, name: "Amit" },
  { id: 2, name: "Rahul" }
];

arr.sort((a, b) => {
  if (a.name && b.name) {
    return a.name.localeCompare(b.name);
  } else if (!a.name && b.name) {
    return -1;
  } else if (a.name && !b.name) {
    return 1;
  } else {
    return a.id - b.id;
  }
});

console.log(arr);

Output:

[
  { id: 1, name: 'Amit' },
  { id: 2, name: 'Rahul' },
  { id: 3, name: 'Rohit' }
]

Approach 2: Using Array.prototype.reduce and Array.prototype.splice

In this approach, Sort an array with optional properties using `Array.prototype.reduce` and `Array.prototype.splice`. Iterate through each element, insert it into the sorted array considering the presence and absence of optional properties. Returns the sorted array, ensuring proper handling of optional properties during sorting.

Syntax:

array.reduce( myFunction, initialValue );
array.splice( myFunction, initialValue )

Example: Here, we are Sorting an array of arrays numerically using the first element. Uses `reduce` and `splice` to insert elements into the sorted array. Returns the sorted array.

Javascript
type MyObject = number[];

const arr: MyObject[] = [
  [3, 4, 5], 
  [1, 2],
  [6, 7, 8]
];

// Sorting function using reduce and splice
const result = arr.reduce((acc: MyObject[], curr: MyObject) => {
      const index = acc.findIndex((obj: MyObject) => {
        return curr.length && obj.length ? curr[0] < obj[0] : 
            obj.length === 0;
  });
  if (index !== -1) {
    acc.splice(index, 0, curr);
  } else {
    acc.push(curr);
  }
  return acc;
}, []);

console.log(result);

Output:

[ [ 1, 2 ], [ 3, 4, 5 ], [ 6, 7, 8 ] ]

Approach 3: Using custom sorting function with ternary operator

This approach involves defining a custom sorting function that compares elements based on their optional properties. The ternary operator is used to handle cases where properties are undefined, ensuring correct sorting by comparing values or falling back to another property for comparison.

Example: In this example we sort an array of objects based on the presence of a ‘name’ property. It prioritizes names and sorts by ‘id’ if ‘name’ is absent.

JavaScript
interface MyObject {
    id: number;
    name?: string;
}

const array: MyObject[] = [
    { id: 3, name: "Rohit" },
    { id: 1 },
    { id: 2, name: "Rahul" }
];

array.sort((a, b) => {
    if (a.name === undefined && b.name === undefined) return a.id - b.id;
    if (a.name === undefined) return 1;
    if (b.name === undefined) return -1;
    return a.name.localeCompare(b.name);
});

console.log(array);

Output:

[ { id: 2, name: 'Rahul' }, { id: 3, name: 'Rohit' }, { id: 1 } ]


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads