Sort Array of Objects by Property with Undefined Values in TypeScript

In TypeScript, sorting an array of objects by property with undefined values by comparing the defined values precedes those with the undefined ones.

Below are the approaches to sort the array of objects by property with undefined values in TypeScript:

Table of Content

  • Using Array.reduce and findIndex method
  • Using the Array.sort method
  • Using Array.prototype.sort method with custom comparison

Using Array.reduce and findIndex method

In this approach, we are using the Array.reduce() method to iterate over the original array and construct a new array (acc) in sorted order based on the “rank” property. The findIndex function is used to determine the correct position for inserting the current item, considering undefined values, resulting in a sorted array by ” “ with items having defined ranks first and those with rank: undefined.

Syntax:

array.reduce((accumulator, currentValue, index, array) => {/* code*/}, initialValue); 
array.findIndex((element, index, array) => {/* code*/}); 

Example: The below example uses the Array.reduce method to Sort an array of objects by property with undefined values in TypeScript.

Javascript
interface Obj {
    name: string;
    rank?: number;
}
const data: Obj[] = [
    { name: 'DSA', rank: 3 },
    { name: 'Python', rank: 1 },
    { name: 'React', rank: undefined },
    { name: 'TypeScript', rank: 2 },
];
const res = data.reduce < Obj[] > ((acc, item) => {
    const index = acc.findIndex(temp =>
        (
            item.rank === undefined
            &&
            temp.rank === undefined
        )
        ||
        (
            item.rank !== undefined
            &&
            temp.rank !== undefined
            &&
            item.rank < temp.rank
        )
    );
    if (index === -1) {
        acc.push(item);
    }
    else {
        acc.splice(index, 0, item);
    }
    return acc;
}, []);
console.log(res);

Output:

  [{
   "name": "Python",
   "rank": 1
 }, {
   "name": "TypeScript",
   "rank": 2
 }, {
   "name": "DSA",
   "rank": 3
 }, {
   "name": "React",
   "rank": undefined
 }] 

Using the Array.sort method

In this approach, we are using the Array.sort method to sort an array of objects by the “rank” property. We first map each object to include its original index, then perform the sorting based on the numeric value of “rank” (undefined as Infinity), followed by the original index. Finally, we map back to the original objects to get the sorted array with items having defined ranks first, and those with rank: undefined.

Syntax:

array.sort((a, b) => a - b);

Example: The below example uses the Array.sort method to Sort an array of objects by property with undefined values in TypeScript.

Javascript
interface Obj {
    name: string;
    rank?: number;
}
const data: Obj[] = [
    {
        name: 'DSA',
        rank: 3
    },
    {
        name: 'Python',
        rank: 1
    },
    {
        name: 'React',
        rank: undefined
    },
    {
        name: 'TypeScript',
        rank: 2
    },
];
const res = data
    .map((item, index) => ({ index, item }))
    .sort((a, b) => {
        const aRank = a.item.rank !== undefined ? a.item.rank : Infinity;
        const bRank = b.item.rank !== undefined ? b.item.rank : Infinity;
        return aRank - bRank || a.index - b.index;
    })
    .map(entry => entry.item);
console.log(res);

Output:

  [{
   "name": "Python",
   "rank": 1
 }, {
   "name": "TypeScript",
   "rank": 2
 }, {
   "name": "DSA",
   "rank": 3
 }, {
   "name": "React",
   "rank": undefined
 }] 

Using Array.prototype.sort method with custom comparison

In this approach, we’ll use the Array.prototype.sort method to sort the array of objects by the “rank” property. We’ll customize the comparison function to handle undefined values by treating them as the highest possible value. This ensures that objects with defined ranks precede those with undefined ranks.

Example: Below is the implementation using the Array.prototype.sort method.

JavaScript
interface Obj {
    name: string;
    rank?: number;
}

const data: Obj[] = [
    { name: 'DSA', rank: 3 },
    { name: 'Python', rank: 1 },
    { name: 'React', rank: undefined },
    { name: 'TypeScript', rank: 2 },
];

const sortedData = data.sort((a, b) => {
    const aRank = a.rank !== undefined ? a.rank : Infinity;
    const bRank = b.rank !== undefined ? b.rank : Infinity;
    return aRank - bRank;
});

console.log(sortedData);

Output:

[{
  "name": "Python",
  "rank": 1
}, {
  "name": "TypeScript",
  "rank": 2
}, {
  "name": "DSA",
  "rank": 3
}, {
  "name": "React",
  "rank": undefined
}] 


Contact Us