ArticleZip > How To Sort Object Array Based On Key In Typescript Duplicate

How To Sort Object Array Based On Key In Typescript Duplicate

Sorting object arrays in TypeScript can greatly enhance the readability and organization of your code. In this guide, we will delve into the process of sorting an object array based on a specific key in TypeScript while also addressing the scenario of dealing with duplicate values.

Before diving into the sorting process, let's create a sample object array that we can work with:

Typescript

const items = [
    { name: 'Apple', quantity: 5 },
    { name: 'Orange', quantity: 3 },
    { name: 'Banana', quantity: 7 },
    { name: 'Apple', quantity: 2 },
    { name: 'Banana', quantity: 5 },
];

To sort this object array based on the "name" key, and then by the "quantity" key in case of duplicate "name" values, we can use the following code snippet:

Typescript

items.sort((a, b) => {
    if (a.name !== b.name) {
        return a.name < b.name ? -1 : 1;
    }
    return a.quantity - b.quantity;
});

In this code snippet, we make use of the `sort()` method available for arrays in JavaScript/TypeScript. The `sort()` method takes a comparator function that compares two elements of the array (`a` and `b` in this case) and returns a negative value if `a` should come before `b`, a positive value if `a` should come after `b`, and zero if the order should remain unchanged.

The comparator function first checks if the "name" property of `a` and `b` are different. If they are different, it sorts based on the "name" property using a simple string comparison. If the "name" properties are the same, it further sorts based on the "quantity" property by subtracting the quantity of `a` from the quantity of `b`.

By applying this sorting logic, the `items` array will now be sorted first by the "name" in ascending order and then by the "quantity" in ascending order for objects with the same "name".

You can easily modify this comparator function to suit your specific sorting requirements based on different keys or sorting orders.

Remember, sorting object arrays in TypeScript based on specific keys can help you manage and display data more efficiently, providing clarity and structure to your applications.

Implement this sorting technique in your TypeScript projects to keep your data organized and easily accessible. Feel free to experiment with different sorting criteria and customization options to align with your project's needs.