Open In App

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

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

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






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

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




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]

Article Tags :