Open In App

How to move Null Values at the end Regardless of the Sorting Direction in TypeScript ?

Last Updated : 14 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

A few times, we face situations where we need to sort values with null values in them. In this, we sort it and move the null values to the end regardless of the sorting direction. In TypeScript, achieving this requires special handling and sowe are going to discuss those processes.

These are the following ways:

Using custom Sorting Function

  • Define a function that compares two values, taking into account null values.
  • If both values are null, return 0 to indicate they are equal.
  • If either value is null, make sure the non-null value appears before the null values.
  • Use this custom sorting function with the Array.prototype.sort() method to sort the array.

Example: This example shows the implementation of the above-explained approach.

Javascript




const arr: (number | null)[] = [3, 7, null, 2, null, 5, 1, 8, null];
 
function customSort(a: number | null, b: number | null): number {
    if (a === null && b === null) return 0;
    if (a === null) return 1;
    if (b === null) return -1;
    return a - b;
}
 
arr.sort(customSort);
 
console.log(arr);


Output:

[1, 2, 3, 5, 7, 8, null, null, null]

Using Array Manipulation methods

  • Use Array.prototype.filter() to create two separate arrays: one containing non-null values and another containing null values.
  • Sort the array of non-null values using the regular sorting mechanism.
  • Concatenate the sorted non-null values with the array of null values to create the final sorted array with null values at the end.

Example: This example shows the implementation of the above-explained approach.

Javascript




const arr: (number | null)[] = [null, 3, 7,
    null, 2, null, 5, 1, 8, null];
 
function customSort(a: number | null, b: number | null): number {
    if (a === null && b === null) return 0;
    if (a === null) return 1;
    if (b === null) return -1;
    return a - b;
}
 
arr.sort(customSort);
 
console.log(arr);


Output:

[1, 2, 3, 5, 7, 8, null, null, null]


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads